Passing ViewBag (has list of int type) to Controller

748 views Asked by At

I am trying to pass list of int type to Controller on jquery load, but not successfull. Here is my code:

function Addcov() {
    var dt = '@ViewBag.dt';
    @{
        List<int> covtypes = new List<int>();
        foreach (var item in ViewBag.CovTypes)
        {
            covtypes.Add(item);
        }
    }
    alert('@covtypes');

    $("#Form").dialog({
         autoOpen: true,
         width: 1000,
         resizable: false,
         title: 'Add',
         modal: true,
         open: function () {
             $(this).load(
                 '../controller/AddAction', 
                 { fromDate: dt, CovTypes: JSON.stringify('@covtypes') },
                 function (response, status, xhr) {});
             },
             buttons: {}
        });
    }
3

There are 3 answers

0
Akshita On

i can suggest put values of ViewBag [List of int] as csv in html element and later convert them to array of int and pass to controller as

<input type="hidden" id="list" value="@ViewBag.CovTypes.Aggregate((x,y)=>x+","+y)" />

function Addcov() {
 var data=$("#list").val().split(",")map(function(i,e){   return parseInt(e);          });

$("#Form").dialog({
     autoOpen: true,
     width: 1000,
     resizable: false,
     title: 'Add',
     modal: true,
     open: function () {
         $(this).load(
             '../controller/AddAction', 
             { fromDate: dt, CovTypes:JSON.stringify(data) },
             function (response, status, xhr) {});
         },
         buttons: {}
    });
 }
0
Ni Ma On

it would be helpful if you've written the calling method on your controller, but in your case you're sending a Get request , therefore, you might indicate that this values are coming from URI, like follows:

public ActionResult AddAction(object fromDate, [FromUri] List<int> arr)
2
Barr J On

I might see your problem, the path. debug and make sure that the path you are passing is correct and that the data actually being passed through the covtypes.

The main issue that I see here, is the path, which is not passed correctly. Try with the full path and see what happens.