gpt4 book ai didi

c# - 模型与非顺序索引的 JSON 数组/对象绑定(bind)

转载 作者:太空宇宙 更新时间:2023-11-03 15:51:04 26 4
gpt4 key购买 nike

引用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com