MVC如何接收来自JSON的对象数组

MVC How to receive an object array that comes from JSON?

本文关键字:对象 数组 JSON 何接收 MVC      更新时间:2023-09-26

我正试图将一个对象数组发送到我的控制器,但遇到了一些困难。

它正在发送数组,当传递到控制器时,数组的对象计数似乎也可以。但如果你看对象内部,对象的所有属性都是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"}