非顺序集合绑定 [英] Non-sequential collection binding
问题描述
将 MVC 视图中动态创建的元素集合绑定到 MVC 4 中的集合的最佳方法是什么.我知道以前的版本要求元素如下所示:
What is the best way to bind a dynamically created collection of elements in an MVC view to a collection in MVC 4. I know previous versions have required that the elements look like this:
<input name="Categories[0].CategoryID" type="hidden" value="123" />
<input name="Categories[0].CategoryName" type="hidden" value="Music" />
<input name="Categories[1].CategoryID" type="hidden" value="456" />
<input name="Categories[1].CategoryName" type="hidden" value="Movies" />
但是当您动态添加新元素并删除它们时,事情很快就会变得混乱.
But when you are dynamically adding new elements and removing them, things get out of sequence pretty quickly.
MVC 4 是否添加了一种绑定到非顺序集合的方法?
Does MVC 4 add a way to bind to a non-sequential collection?
推荐答案
从 MVC2 开始支持非顺序集合索引,您只需要一个单独的隐藏字段,它将保存具有 name
架构的索引:CollectionName.Index
:
Non sequential collection indices supported since MVC2 you just need to have a separate hidden field which will hold the index with the name
schema: CollectionName.Index
:
例如:
<input type="hidden" name="Categories.Index" value="3" />
<input name="Categories[3].CategoryID" type="hidden" value="123" />
<input name="Categories[3].CategoryName" type="hidden" value="Music" />
<input type="hidden" name="Categories.Index" value="1" />
<input name="Categories[1].CategoryID" type="hidden" value="456" />
<input name="Categories[1].CategoryName" type="hidden" value="Movies" />
您可以在此处找到有关该主题的更多信息:模型绑定到列表
You can find more info about the topic here: Model Binding To A List
这篇关于非顺序集合绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!