问题描述
|
public class PostModel {
public string Value { get; set; }
public IList<TestModel> TestValues { get; set; }
}
public class TestModel {
public string Value { get; set; }
}
jQuery脚本:
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\");
}
如何绑定嵌套对象?
解决方法
发布到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,...);