views:

52

answers:

2

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.

+2  A: 

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);
}
Darin Dimitrov
genius, thank you! It seems there is a bug in getJson with 1.4.2, see http://forum.jquery.com/topic/getjson-breaks-with-1-4-2-when-parameter-argument-is-an-array
fearofawhackplanet
This is not a bug. It is a breaking change from previous the version. That's why they introduced the `traditional` parameter.
Darin Dimitrov
A: 

Unfortunately, while it seems that jquery provides a "traditional" flag to toggle this behavior on jQuery.ajax, it does not on jQuery.getJSON. One way to get around this would to be set the flag globally:

jQuery.ajaxSettings.traditional = true;

See the documentation for jQuery.param: http://api.jquery.com/jQuery.param/ Also see the release notes for this change: http://jquery14.com/day-01/jquery-14 (search for 'traditional')

jrduncans