C# MVC 模型绑定到 post 上的索引数组
C# MVC model binding to indexed array on post
是否可以将模型绑定到已发布的损坏索引数组?
<input type='text' name='question[3]' value='answer to question 3' />
<input type='text' name='question[5]' value='whatever here' />
<input type='text' name='question[18]' value='a different ansewr' />
<input type='text' name='multiquestions[4][1]' value='question 4 part 1' />
<input type='text' name='multiquestions[4][2]' value='question 4 part 2' />
理想情况下,我希望我的模型符合(尽管输入这个我可以看到稀疏数组键是一个问题):
public class MyModel {
public Dictionary<int,string> questions {get;set;}
public Dictionary<int, Dictionary<int, string>> multiquestions {get;set;}
}
让 MVC 模型绑定器完成繁重的工作:
public ActionResult MyAction(MyModel model) {...}
但它似乎只适用于未损坏的索引。我需要索引,因为这是我将数据放入数据库的方式。
我宁愿没有一系列描述模型的隐藏字段,例如<input type=hidden name='questions[0].Key' value='3' /><input type=hidden name='questions[0].Value' value='answer to question 3' />
我已经阅读了关于该主题的 Hanselman blog post,它建议编写一个自定义模型活页夹,如果开箱即用都行不通,但不确定从哪里开始编写自定义活页夹,我希望有一些 MVC 可以做的事情 "out of the box",或者 somoene 已经解决了这个问题
也许您可以在访问值之前检查 count 或 null
经过更多的搜索,事实证明不使用 int 作为字典键是诀窍。
使用 Dictionary<string, string>
和 Dictionary<string, Dictionary<string, string>>
,模型绑定将按我预期的方式工作,当我在服务器上时,我需要将密钥解析为 int。
是否可以将模型绑定到已发布的损坏索引数组?
<input type='text' name='question[3]' value='answer to question 3' />
<input type='text' name='question[5]' value='whatever here' />
<input type='text' name='question[18]' value='a different ansewr' />
<input type='text' name='multiquestions[4][1]' value='question 4 part 1' />
<input type='text' name='multiquestions[4][2]' value='question 4 part 2' />
理想情况下,我希望我的模型符合(尽管输入这个我可以看到稀疏数组键是一个问题):
public class MyModel {
public Dictionary<int,string> questions {get;set;}
public Dictionary<int, Dictionary<int, string>> multiquestions {get;set;}
}
让 MVC 模型绑定器完成繁重的工作:
public ActionResult MyAction(MyModel model) {...}
但它似乎只适用于未损坏的索引。我需要索引,因为这是我将数据放入数据库的方式。
我宁愿没有一系列描述模型的隐藏字段,例如<input type=hidden name='questions[0].Key' value='3' /><input type=hidden name='questions[0].Value' value='answer to question 3' />
我已经阅读了关于该主题的 Hanselman blog post,它建议编写一个自定义模型活页夹,如果开箱即用都行不通,但不确定从哪里开始编写自定义活页夹,我希望有一些 MVC 可以做的事情 "out of the box",或者 somoene 已经解决了这个问题
也许您可以在访问值之前检查 count 或 null
经过更多的搜索,事实证明不使用 int 作为字典键是诀窍。
使用 Dictionary<string, string>
和 Dictionary<string, Dictionary<string, string>>
,模型绑定将按我预期的方式工作,当我在服务器上时,我需要将密钥解析为 int。