Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use EditorFor inside a foreach

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>
like image 639
Jeremy Avatar asked Dec 31 '09 05:12

Jeremy


3 Answers

@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])
 }
like image 84
Alexander Taran Avatar answered Nov 03 '22 15:11

Alexander Taran


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

like image 36
Jamie Avatar answered Nov 03 '22 16:11

Jamie


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.

like image 1
David Silva-Barrera Avatar answered Nov 03 '22 14:11

David Silva-Barrera