-1

I am trying to get and store the Ids of all the selected check-boxes in the JavaScript object. And then passing this object as a data to my JSON Action. I am able to successfully get the Ids of all the selected check-boxes, but when I am passing this object to my action I am getting null. Following is my code:

$("#btnSave").on('click', function () {

   var selected = [];

   $('input:checked').each(function () {
       selected.push($(this).attr('id'));
   });

   $.ajax({
       url: '@Url.Action("SaveRecords", "Users")',
       data: { ids: selected },
       cache: false,
       type: "GET",
       success: function (data) {}
   });

});

My Action:

public JsonResult SaveRecords(List<int> ids) //Here I'm getting Null.
{
    return Json(true, JsonRequestBehavior.AllowGet);
}
John Adam
  • 220
  • 2
  • 14

1 Answers1

0

As suggested in the comments, since you are saving data POST is more appropriate than GET. Also, I think you will save yourself some trouble by using JSON as input - you're already using it as output format from the action. This means your AJAX call will look like this:

$.ajax({
   type: 'POST',
   url: '@Url.Action("SaveRecords", "Users")',
   contentType: 'application/json',
   data: JSON.stringify(selected),
   success: function (data) { /* ... */ }
});

When I say "save yourself trouble by using JSON as input" I mean that model binding collections and complex types in MVC can be a bit tricky when sending data as a form post - google it and you'll see that there are several implementation characteristics to be aware of. In my experience, using JSON for structured data posted with AJAX just works much more like what you would expect.

Anders Fjeldstad
  • 10,724
  • 2
  • 33
  • 50