引用 Phil Haack 的 article ,我可以在不使用顺序索引的情况下绑定(bind)到 View 模型,例如:
public class FooViewModel
{
public int Id { get; set }
public decimal Amount { get; set; }
public ICollection<Bar> Bars { get; set; }
}
public class BarViewModel
{
public int Id { get; set; }
public string Baz { get; set; }
}
我的Foo/Edit.cshtml
:
<input type="hidden" name="Bars.Index" value="123" />
<input type="text" name="Bars[123].Baz" value="Chips" />
<input type="hidden" name="Bars.Index" value="caliente" />
<input type="text" name="Bars[caliente].Baz" value="Salsa" />
当通过正常的 HTTP Post 请求提交表单时,Bars
被正确填充。但是,如果我将表单序列化为 JSON,即使用 serializeJSON
序列化表单然后通过 AJAX 提交,JSON 负载不正确:
{
"Id": 1,
"Amount": 26.4,
"Bars": {
"123": {
"Id": 1,
"Baz": "Chips"
},
"caliente": {
"Id": 2,
"Baz": "Salsa"
},
"Index": "caliente" <-- Extra property in the JSON object
}
}
无法绑定(bind)到我的 FooViewModel
中的 Bars
属性(Bars
变为 null)。使用具有非顺序索引的 JSON 对象时,有什么想法可以绑定(bind)集合属性吗?
最佳答案
尝试使用
Dictionary<string, Bar>
对于您的 Bars 参数,它应该能够理解您正在获取的序列化 JSON。
关于c# - 模型与非顺序索引的 JSON 数组/对象绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25783883/