Home » ASP » ASP.MVC » How to use Asp.Net DisplayFor or EditorFor within a loop

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

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.


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.

		foreach (var contestListItemViewModel in Model.Contests)
				<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>

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.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.