How to use EditorFor inside a foreach

Jeremy picture Jeremy · Dec 31, 2009 · Viewed 20.6k times · Source

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>

Answer

Alexander Taran picture Alexander Taran · Jan 1, 2010
@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])
 }