Passing a Collection to EditorFor in ASP.NET MVC

让人想犯罪 __ 提交于 2019-12-03 02:59:58

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!