2013-03-05 24 views
2

我有我的看法如下代碼:Html.EditorFor MVC4中的子對象?

@foreach (var parent in Model.Parents) 
     {  
      @foreach (var child in parent.Children) 
       { 

       @Html.TextAreaFor(c => child.name) 

       }     
     } 

形式的其他文字區域被節省了罰款,但提交表單的時候,在我的控制器POST方法得到一個視圖模型具有無效親場。任何想法爲什麼?

回答

6

如果希望集合綁定,則不能使用foreach循環。你必須使用for循環:

@for (int i = 0; i < Model.Parents.Count; i++) { 
    @for (int j = 0; j < Model.Parents[i].Children.Count; j++) { 
     @Html.TextAreaFor(x => x.Parents[i].Children[j].name) 
    } 
} 

另外,您可以使用編輯器模板家長(甚至其他兒童)。這需要你建立一個父模型模板,並把它在你的EditorTemplates文件夾中,然後調用它像這樣:

@Html.EditorFor(x => x.Parents) 

MVC將採取列舉的關懷和約束力。兒童列表也可以做同樣的事情。

下面是使用它們(我無法找到一個mvc4版)一個MVC教程:http://coding-in.net/asp-net-mvc-3-how-to-use-editortemplates/

+0

謝謝西蒙。我收到一個錯誤,因爲Children是一個ICollection,而我所擁有的只是我的viewModel中的父母。任何想法我怎麼能「列出」父母的一切,或以某種方式解決這個問題? – RobVious 2013-03-05 21:04:13

+0

要麼更改爲IList,要麼使用編輯器模板。編輯器模板可以與IEnumerables一起使用。檢查這個答案的想法使用:http://stackoverflow.com/questions/4652457/asp-net-mvc-problem-with-editortemplate-for-icollectiont-mapped-to-enum?answertab=votes#tab-top – 2013-03-05 21:37:29

+0

我將不得不使用兩個模板,對吧?一個給父母,一個給孩子? – RobVious 2013-03-05 21:44:45