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

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.

Leave a Comment