MVC如何接收来自JSON的对象数组
MVC How to receive an object array that comes from JSON?
我正试图将一个对象数组发送到我的控制器,但遇到了一些困难。
它正在发送数组,当传递到控制器时,数组的对象计数似乎也可以。但如果你看对象内部,对象的所有属性都是null
这怎么可能?
JavaScript:
function callme(results) {
for (var i = 0; i < results.length; i++) {
var endRes = {
Id: results[i].id,
Icon: results[i].icon
};
jsonObj.push(endRes);
}
sendPackage(jsonObj);
}
function sendPackage(jsonObj) {
$.ajax({
type: "POST",
url: '../../Home/RegisterList',
data: { List: jsonObj },
cache: false,
dataType: "json",
error: function (x, e, data) {
alert(data);
}
});
}
控制器:
[HttpPost]
public JsonResult RegisterList(ICollection<DetailsModel> List)
{
foreach (var i in List) ....... // other process will be here
............................... // other process will be here
return Json(new { message = "OK" });
}
型号:
public class DetailsModel
{
public string Id { get; set; }
public string Icon { get; set; }
}
好的,我昨晚用Newton的JSON.NET解决了这个问题(你可以从NuGet获得它)。我已经将数组字符串化,并将其作为字符串与控制器一起接收。最后,我使用json.net将这个字符串转换(反序列化)为一个集合。
要字符串化:使用相同的代码,但用更改json请求的数据部分
data: { List : JSON.stringify(jsonObj) }
最终收到:
using Newtonsoft.Json;
public JsonResult RegisterList(string List)
{
ICollection<DetailsModel> jsonModel = JsonConvert.DeserializeObject<ICollection<DetailsModel>>(List);
}
瞧;您有一个名为jsonModel的集合!
不幸的是,列表的模型绑定在MVC中并不那么好和明显。请参阅:http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
以这种方式传递列表有效:
数据:{"List[0].Id":"1","List[0].Icon":"test"}
相关文章:
- Javascript(Angular)从一个对象数组到第二个数组查找值
- 在Javascript中转换对象数组
- 在JavaScript中通过索引从对象数组中获取值
- Backbone虹吸以获取对象数组
- 如何在DataTables 2.1中迭代对象数组
- Javascript-根据赋值顺序,按键合并对象数组
- 将事件附加到对象/数组
- jQuery$.inArray()总是返回-1和一个对象数组
- javascript处理一个对象数组以获得一个新的对象数组
- javascript在数组中获取对象数组中键的所有不同值
- 在对象数组中查找多个值的d3范围
- Undercore.js获取对象数组中键对象的值
- 在mongoose中使用正则表达式在对象数组中进行查询搜索
- 如何通过json对象数组为嵌套对象赋值
- 如何循环通过2个对象数组并通过匹配id进行合并
- 为对象数组创建列表项
- 如何使用javascript合并两个对象数组
- JSON到对象数组,并向每个对象添加项
- JavaScript:从对象数组中获取唯一值及其计数
- 按不同项目对对象数组进行排序