I have the following where I'm trying to send list/array to MVC controller method:
var id = []; var inStock = []; $table.find('tbody>tr').each(function() { id.push($(this).find('.id').text()); inStock.push($(this).find('.stocked').attr('checked')); }); var params = {}; params.ids = id; params.stocked = inStock; $.getJSON('MyApp/UpdateStockList', params, function() { alert('finished'); });
in my contoller:
public JsonResult UpdateStockList(int[] ids, bool[] stocked) { }
both paramaters are null.
Note that if I change the params to single items
params.ids = 1; params.stocked = true; public JsonResult UpdateStockList(int ids, bool stocked) { }
then it works ok, so I don't think it's a routing issue.
Try setting the traditional
flag:
$.ajax({ url: '/home/UpdateStockList', data: { ids: [1, 2, 3], stocked: [true, false] }, traditional: true, success: function(result) { alert(result.status); } });
works fine with:
public ActionResult UpdateStockList(int[] ids, bool[] stocked) { return Json(new { status = "OK" }, JsonRequestBehavior.AllowGet); }
Besides calling .ajax()
instead of .getJSON()
as Darin suggests or setting the global jQuery.ajaxSettings.traditional
to true
as jrduncans suggests, you can also pass the result of calling the jQuery .param()
function on your params
object:
var id = []; var inStock = []; $table.find('tbody>tr').each(function() { id.push($(this).find('.id').text()); inStock.push($(this).find('.stocked').attr('checked')); }); var params = {}; params.ids = id; params.stocked = inStock; $.getJSON('MyApp/UpdateStockList', $.param(params, true), function() { alert('finished'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With