Simple DisplayTemplate for “Status Code” columns in ASP.NET MVC

The following example shows how to create and use a custom DisplayTemplate for status code type columns in an ASP.NET MVC application.

Before DisplayTemplate

After DisplayTemplate

   

 Display Templates

Display templates are cshtml or ascx partials that have a name that often has the same name as the type they’re going to override the default templates provided by MVC.   The name doesn’t need to be the same as the type if UIHints are used in the Model.

How to create and use a new DisplayTemplate

  1. Create the folder
  2. Code the DisplayTemplate partial view (ascx or cshtml)
  3. Add UIHint (system annotations) to your model to indicate where DisplayTemplate should be used
  4. Add DisplayFor HTMLHelper code to views.

 

 

Create view “StatusCode.ascx” to the DisplayFormats folder

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<% if (Model == "A") { %>
 Active
<% } else if (Model == "I") { %>
 Inactive
<% } else if (Model == "P") { %>
 Pending
<% } else if (Model == "N") { %>
New
<% } else { %>

<% } %>

 

Add the UIHint to your model on the status code column.  The name “StatusCode” matches the name of the DisplayTemplate and will cause MVC to use it when using built in helpers for DisplayFor in the view. Note that I fully qualified the UIHint with namespace for illustration purposes only.  Add the namespace with the usings at the top of your model instead.

 

 

 

 

 

 

To use the DisplayTemplate in views simply use one of the built in DisplayFor HTMLHelpers.

<%: Html.DisplayFor(modelItem => item.createdate) %>

 

Summary: The example shown above uses DisplayTemplate with the following functionality:

  • Displays status code description for status code values (e.g. A = Active; I = Inactive)
  • Hard coded key and value pairs for simplicity.
  • Displays space if no status code value exists (field is empty)

Tip:  Factors to consider when deciding whether to use DisplayTemplate vs HTMLHelper

  • HtmlHelpers can protect you from global design changes that break custom markup throughout an application.
  • HtmlHelpers can allow you to maximize the DRY (Don’t repeat yourself) principle.
  • HtmlHelpers should be used when there is a lot of special logic or coding that affects the markup.
  • Partial Views (DisplayTemplates) should be used when the markup is simple and there isn’t much logic or special functionality.

Tags:

One response

  1. Great beat ! I would like to apprentice while you amend your web site, how could i subscribe for a weblog web site? The account helped me a acceptable deal. I have been a little bit familiar of this your broadcast offered vivid clear idea

Leave a Reply to website Cancel reply

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