Question

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>
Was it helpful?

Solution

@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])
 }

OTHER TIPS

@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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top