Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am loving MVC 2. The whole thing just fits the web so well.

There is one piece of functionality, however, that I am unable to coax out of the Html.DisplayFor() function:

<@ Page Inherits="ViewPage<IEnumerable<Foo>>">  <% foreach(var item in Model) { %>      <%: Html.DisplayFor(item.BarBaz) %>  <% } %> 

I need to be able to use the DisplayTemplate for this value. Is there a way to do this?

like image 859
John Gietzen Avatar asked Aug 05 '10 22:08

John Gietzen


Video Answer


2 Answers

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.

like image 52
John Gietzen Avatar answered Sep 21 '22 02:09

John Gietzen


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);    } %> 
like image 27
sgriffinusa Avatar answered Sep 20 '22 02:09

sgriffinusa