How to use EditorFor inside a foreach

 ̄綄美尐妖づ 提交于 2019-11-26 16:05:06

问题


I have a model:

public class MyListModel
{
    public int ID {get;set;}
    public List<User> Users{get;set;}
}

How do I use the Html.EditorFor method inside a foreach?

@model MyListModel
<table>
  <tr>
    <th></th>
  </tr>
  @foreach (var item in Model.Users) {
     <tr>
       <td>
          @Html.EditorFor(item.Enabled)
       </td>
     </tr>
  }
</table>

回答1:


@Html.EditorFor(x=> item.Enabled)

It's been pointed out many times that posting such a model back to server will not work in mvc by default. For properly editing with EditorFor in a loop - for should be used as in:

 @for(var i = 0; i< Model.Users.Count;i++){
      Html.EditorFor(i=>Model.Users[i])
 }



回答2:


@for (var i = 0; i < Model.Users.Count; i++)
{
<tr>
    <td>@Html.EditorFor(model => model.Users[i].Enabled)</td>
    <td>@Html.EditorFor(model => model.Users[i].FirstName)</td>
    <td>@Html.EditorFor(model => model.Users[i].LastName)</td>
</tr>
}

Plus some hidden variables for at least one property of the User are required:

@for (var i = 0; i < Model.Users.Count; i++)
{
    @Html.HiddenFor(model => model.Users[i].FirstName)
}

Not what you would call elegant but it works with respect to binding in your post action.




回答3:


Is there any other reason (example apart) for explicitly using the foreach yourself? You could make a Custom Editor (or Display) helper for User class and make @Html.EditorFor(model=>model.Users). Razor will use the foreach internally for processing each element with your Custom Helper.

Just an idea for those visiting the question with really no clue how manage this cases.



来源:https://stackoverflow.com/questions/1983999/how-to-use-editorfor-inside-a-foreach

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