使用jQuery getJson将列表/数组作为参数发送

我有以下我正在尝试将列表/数组发送到MVC控制器方法:

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'); }); 

在我的控制器中:

 public JsonResult UpdateStockList(int[] ids, bool[] stocked) { } 

两个参数都是空的。

请注意,如果我将参数更改为单个项目

 params.ids = 1; params.stocked = true; public JsonResult UpdateStockList(int ids, bool stocked) { } 

然后它工作正常,所以我不认为这是一个路由问题。

尝试设置traditional标志:

 $.ajax({ url: '/home/UpdateStockList', data: { ids: [1, 2, 3], stocked: [true, false] }, traditional: true, success: function(result) { alert(result.status); } }); 

适用于:

 public ActionResult UpdateStockList(int[] ids, bool[] stocked) { return Json(new { status = "OK" }, JsonRequestBehavior.AllowGet); } 

除了像Darin建议的那样调用.ajax()而不是.getJSON() ,或者像jrduncans建议的那样将全局jQuery.ajaxSettings.traditional设置为true ,你还可以在params对象上传递调用jQuery .param()函数的结果:

 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'); }); 

不幸的是,虽然看起来jquery提供了一个“传统”标志来在jQuery.ajax上切换这种行为,但它并没有在jQuery.getJSON上。 解决这个问题的一种方法是在全球范围内设置标志:

jQuery.ajaxSettings.traditional = true;

请参阅jQuery.param的文档: http : //api.jquery.com/jQuery.param/另请参阅此更改的发行说明: http : //jquery14.com/day-01/jquery-14 (搜索’传统的“)

在视图中,生成多个命名字段 (不是id ,因为id应该是每个字段唯一的),注意使用Name而不是name

 @foreach (var item in Model.SomeDictionary) { @Html.TextBoxFor(modelItem => item.Value.SomeString, new { Name = "someString[]" }) } 

然后使用jQuery检索输入字段值, 所以 :

 var myArrayValues = $('input[name="someString[]"]').map(function () { return $(this).val(); }).get(); 

您可以直接在jQuery / AJAX中使用它,如下所示:

 $.ajax({ type: "POST", url: "/MyController/MyAction", dataType: 'json', data: { someStrings: $('input[name="someString[]"]').map(function () { return $(this).val(); }).get(), someDates: $('input[name="someDate[]"]').map(function () { return $(this).val(); }).get(), 

然后在MVC中的控制器动作中:

 [HttpPost] public JsonResult MyAction(string[] someStrings, DateTime[] someDates...