Templating Html.DisplayFor () in ASP.NET MVC 2

It seems that if you just use Html.DisplayFor(model => model) without templates to represent the information, the resulting markup will look something like this:

 <div class="display-label">first name</div> <div class="display-field">Dan</div> <div class="display-label">last name</div> <div class="display-field">M</div> <div class="display-label">email</div> <div class="display-field"> danm@fakedomain.com </div> 

This has a certain degree of flexibility. If you create CSS classes for display-label and display-field , you can do quite a bit, but what if I wanted to change it to something like this?

 <p> <span class="display-label">first name</span>: <span class="display-field">Dan</span> </p> <p> <span class="display-label">last name</span>: <span class="display-field">M</span> </p> <p> <span class="display-label">email</span>: <span class="display-field"> danm@fakedomain.com </span> </p> 

Note that now attribute-value pairs now appear side by side (instead of individual lines), and there is a colon after each attribute.

Is there a way to create a custom template that will be repeated for each attribute-value pair when the part view is tinted?

I'm not talking about a specific template for a model (for example, a Person template) or a template for a specific property (for example, an EmailAddress template). I want something that just allows me to describe what a pair of attribute values ​​look like, then DispalyFor() should automatically repeat this pattern for each property in my model or view model.

+6
css asp.net-mvc templates templating scaffolding
source share
1 answer

How about overriding an Object template like

  <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> <% if (ViewData.TemplateInfo.TemplateDepth > 3) { %> <%= ViewData.ModelMetadata.SimpleDisplayText %> <% } else { %> <table> <% foreach (ModelMetadata prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForDisplay && !ViewData.TemplateInfo.Visited(pm))) { %> <% if (prop.HideSurroundingHtml) { %> <%= Html.Display(prop.PropertyName) %> <% } else { %> <tr> <td> <div class="display-label" style="text-align: right;"> <%= Html.Label(prop.PropertyName) %> </div> </td> <td> <div class="display-field"> <%= Html.Display(prop.PropertyName) %> <%= Html.ValidationMessage(prop.PropertyName, "*") %> </div> </td> </tr> <% } %> <% } %> </table> <% } %> 

See http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-4-custom-object-templates.html

+9
source share

All Articles