2012-09-05 77 views
7

什麼是在MVC視圖元素的動態創建的集綁定到MVC 4集,我知道以前的版本有要求的元素,看起來就像是最好的方法:非有序集合結合

<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" /> 

但是,當您動態添加新元素並將其刪除時,事情會非常快速地失序。

是否MVC 4添加一種綁定到非順序集合的方法?因爲MVC2支持

回答

11

非連續採集指標,你只需要擁有一個獨立的隱藏字段將舉行該指數與name模式: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" /> 

你可以找到更多信息關於此處的主題:Model Binding To A List

+0

但是,使用Html Helpers時,這看起來確實不太好,因爲您無法使用htmlAttributes控制輸入元素的名稱。 – Dismissile

+0

不,沒有直接支持'HtmlHelpers',但有一些第三方助手像[BeginCollectionItem助手](https://github.com/danludwig/BeginCollectionItem),它可以生成索引隱藏字段和正確的輸入名字給你。 – nemesv

+0

無賴。我希望MVC4會讓這個更容易一點。 – Dismissile