通过 ajax 调用传递自定义模型 *with List<CustClass>*

Pass custom model *with List<CustClass>* through ajax call

我在将 json 字符串传递到控制器中的 jsonResult 时遇到了一些问题。所有一级变量都很好,除了 List<CustClass> 它总是 returns 一个 默认空列表 而它应该用 填充对象列表 (List<>) 我传入了。

ajax 调用类似于:

var model = {
    Id: id,
    Name: name,
    Items: [{
        Name: itemName[0],
        Color: itemColor[0]
    },{
        Name: itemName[1],
        Color: itemColor[2]
    }]
};

$.ajax({
    url: "/@path",
    type: "POST",
    data: JSON.stringify(model),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    cache: false,
    traditional: true
});

使用我的 C# 模型查看

public class MyModel
{
    public int Id { get; set; }
    public string Name { get; set; }

    public class Item {
        public string Name { get; set; }
        public string Color { get; set; }
    }
    public List<Item> Items = new List<Item>();
}

结果:

[HttpPost]
public JsonResult MyResult(MyModel model)
{
    // Do Stuff
}

我在这里做错了什么?这甚至可以做到吗?

不要实例化您的列表以正确映射它。由于模型绑定发生在 class.

实例化之后
public class MyModel
{
    public int Id { get; set; }
    public string Name { get; set; }

    public class Item {
        public string Name { get; set; }
        public string Color { get; set; }
    }
    public List<Item> Items {get; set;}
}