How to use Asp.Net DisplayFor or EditorFor within a loop<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to use Asp.Net DisplayFor or EditorFor within a loop

Posted on: April 22, 2014

You can use the Html Helper to use the template system of Asp.Net MVC. You can have @Html.DisplayFor and @Html.EditorFor. The first one is to display the information into a read only control and the latter is the control that allow to modify the value. Both takes as parameter a Lambda expression of the view Model. Without going into too much detail about where DisplayFor or the EditorFor take their file, just remember that it searches for a folder EditorTemplates or DisplayTemplates in the directory where the view use one of these helpers first and then it goes check for Views>Shared>DisplayTemplates or EditorTemplates.

DisplayForLoop 400x125

But, what if you want to use one of these two method within a loop to show value of a collection inside your model? This collection is from another type of the model and you cannot select from the Lambda expression items within a collection but only property of the model? The trick is to use Lambda for the current page model but not using any of the property. Instead, simple choose the variable your want to use the template item.

1<tbody> @{ foreach (var contestListItemViewModel in Model.Contests) { <tr> <td>@Html.ActionLink(contestListItemViewModel.Name.Current, "Edit", "Contest", new { Area = Constants.Areas.ADMINISTRATOR, id = contestListItemViewModel.Id }, null)</td> <td>@Html.DisplayFor(d => contestListItemViewModel.StartingTime.ToShortDateString())</td> <td>@Html.DisplayFor(d => contestListItemViewModel.EndingTime.ToShortDateString())</td> <td>@Html.DisplayFor(d => contestListItemViewModel.InitialCapital)</td> <td>@Html.DisplayFor(d => contestListItemViewModel.IsUsingStockRules)</td> <td>@Html.DisplayFor(d => contestListItemViewModel.IsUsingShortRules)</td> <td>@Html.DisplayFor(d => contestListItemViewModel.IsUsingOptionRules)</td> </tr> } } </tbody>

As you can see, the code in this example is inside a foreach and I can use the DisplayFor Html Helper. The variable for the expression is "d" but I do not use the "d" variable. Instead, I am using the variable that is populated by the foreach "contestListItemviewModel".

This is the simplest way to use the powerful reusable template system within a loop in Asp.Net MVC.