I have a lengthy form which I have broken to several parts and am using @Html.EditorFor for each section which is working great but need your thoughts on whether this approach c
EditorFor is designed to iterate over collections for you. It does this automatically. When you pass a collection into an EditorFor, it will automatically call your template for each item in the collection.
If you need to setup some rendering for the collection as a whole then you should do this outside of the EditorFor call, either in your view code, or in a partial view which calls your EditorFor.
For instance, if you want to put your code in a table, you would do this (where MyCollection is List<MyItem>
):
_MyCollectionPartial.cshtml
<table>
<tr>
<th>Foo...</th>
...
<tr>
@Html.EditorFor(x => x.MyCollection)
</table>
/Views/Shared/EditorTemplates/MyItem.cshtml
@model MyItem
<tr>
<td>@Html.TextBox(x => x.Foo)</td>
....
</tr>
EDIT:
Perhaps a better way to do this is to use a little known and poorly documented "feature" of Editor templates. And that "feature" is that if you specify a template name as an argument, then it does not iterate over the collection. You can use this form to "wrap" your collection item templates.
/Home/Index.cshtml
.... your html
@Html.EditorFor(model => model.MyCollection, "MyCollectionLayout")
/Views/Shared/EditorTemplates/MyCollectionLayout.cshtml
@model List<MyItem>
<table>
<tr>
<th>Foo...</th>
...
<tr>
@Html.EditorForModel() (Or alternatively @Html.EditorFor(model => model)
</table>
/Views/Shared/EditorTemplates/MyItem.cshtml
@model MyItem
<tr>
<td>@Html.TextBoxFor(x => x.Foo)</td>
....
</tr>
NOTE: I say "feature" because this has generated many questions here on SO about it not iterating over collections when the template name is explicitly specified in the arguments)