How can I use Html.DisplayFor inside of an iterator?

This is an old question, but i guess that someone can get benefits from my solution:

Aspx view

<%@ Page Inherits="ViewPage<IEnumerable<Foo>>" %>

<% foreach (var item in Model) { %>

    <%: Html.DisplayFor(m => item) %>

<% } %>

Razor view

@model IEnumerable<Foo>

@foreach (var item in Model)
{
    Html.DisplayFor(m => item)
}

Since DisplayFor accepts an implicit typed lambda, we can directly indicate the instance to display in the loop.

Finally, i'm agree with Anders E. Andersen's answer for the template usage


Actually, I figured it out. How stupid of me.

This works:

<@ Page Inherits="ViewPage<IEnumerable<Foo>>">

<% foreach(var item in Model) { %>

    <%: Html.DisplayFor(m => item.BarBaz) %>

<% } %>

However, this will not work correctly for Html.HiddenFor and Html.ValueFor. In particular, Html.HiddenFor(m => item.NullableDecimal) will render as <input name="NullableDecimal" value="0" /> and Html.ValueFor(m => item.NullableDecimal, "0.00##) will render as 0.00##. However, if you apply a [DisplayFormat(DataFormatString = "{0:0.00########}" to your view model, then it will suddenly work. For this reason, you're probably best off using Html.Display, Html.Hidden, and Html.Value extensions, since you're less likely to run into scenarios where things fail when someone makes a non-local change.


You can accomplish it by getting away from the foreach and using a regular for loop:

 <% for (int i = 0; i < Model.Count(); i++) { %>

    <%: Html.DisplayFor(p=> p.ElementAt(i).BarBaz) %>

 <%} %>

Another option would be to create a PartialView that took an Foo object and only displayed the information that you wanted.

<% foreach (var item in Model)
   {
       Html.RenderPartial("FooBarBazLine", item);
   } %>