public class PostModel {
public string Value { get; set; }
public IList<TestModel> TestValues { get; set; }
}
public class TestModel {
public string Value { get; set; }
}
var testValue1 = {
Value: "val2"
};
var testValue2 = {
Value: "val3"
};
var model = {
Value: "test",
TestValues: [testValue1 , testValue2]
};
jQuery.post(url, model, function (data) {
alert(data);
}
);
public ActionResult Test(PostModel model)
{
model.Value // is OK, = "test"
model.TestValues// is OK, count = 2
model.TestValues[0].Value // why is null ????
return Content("Ok");
}
如何绑定嵌套对象?
答案 0 :(得分:3)
发布到MVC控制器的json数据必须是表示发布表单的名称和值的键值对的集合。为了绑定到复杂的模型,您需要发送类似的内容。
var jsonData = {};
jsonData['TestValues[0].Value'] = '...';
jsonData['TestValues[1].Value'] = '...'; // binds to model.TestValues[1].Value
jsonData['Value'] = '...'; // binds to model.Value
$.post(url, jsonData, ...);