web 2.0

Display and Editor Templates in ASP.NET MVC 2

In the first version of ASP.NET MVC, I found myself creating a lot of HTML Helpers and Partial Views in order to promote code re-use and to standardize formatting of certain data types across views. For example, let's say that I want every date in my application to use the formatting of “MM/dd/yyyy”. In MVC 1.0, I would have made the following HTML Helper:

public static string FormatDate(this HtmlHelper helper, DateTime value ) {
    return value.ToString( "MM/dd/yyyy" );
}

Once the HTML Helper was ready, I would add the markup to my views:

<%= Html.FormatDate( Model.Date ) %>

Although this code is reusable it can be hard to maintain when you have a large application. It is especially painful to implement when you already have dozens of views and you need to replace the old "HTML.Encode( Model.Date )" code with the new helper method. Fortunately, there is a better way! MVC 2.0 introduced the concept of Display and Editor Templates.

First of all, If you want to take advantage of Display and Editor Templates you must use the DisplayFor and EditorFor methods. Unfortunately, these methods are not used by default when you create a new View using the MVC 2.0 tooling. However, if we are aware of the magic that Display and Editor Templates can provide you would probably format all of your views to use these methods. Here is an example:

<%= Html.DisplayFor( x => Model.Date ) %>

When the code above executes we will get the default serialization for a DateTime value. If we are happy with the results, then no further work is required. However, since we are trying to standardize on our “MM/dd/yyyy” formatting we will have to perform a few additional steps. First of all, we need to create a special folder in our MVC project called DisplayTemplates under the Views/Shared directory:

displaytemplate_dir

Inside that folder we will create a new view named DateTime. We will check the “partial view” and the “strongly-typed view” options…

 addview

Finally, we will modify the contents of the "DateTime.ascx” partial view to contain the following:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime>" %>
<%: Model.ToString( "MM/dd/yyyy" ) %>

When this code runs and MVC encounters a DateTime field being outputted with the DisplayFor method we will get our "MM/dd/yyyy" formatting auto-magically!

So now you may be thinking to yourself….”How does this work?” Well, at runtime when MVC finds the line of code using the "Html.DisplayFor( x => Model.Date )" syntax it will search the Shared/Views/DisplayTemplates folder for any partial view that corresponds to the DateTime date type. In our case, it will find a file named "DateTime.ascx". It will then pass the Model.Date value to the view and format it however we specified it!

So why is this useful? Imagine the scenario where you have a very large MVC app with hundreds of views. The boss comes to your office on a Friday afternoon, twenty minutes before your shift ends and asks if you can change the default formatting of all the DateTime fields. If you were using the DisplayFor syntax, you could simply follow the procedure above and still make it to happy hour in plenty of time. If you are using a HTML Helper, you would probably get stuck in rush hour traffic and all of your friends would be drunk by the time you ordered your first beer!

Finally, keep in mind that MVC 2 also has the EditorFor methods. They work exactly the same way as DisplayTemplates except the views must reside in the Shared/Views/EditorTemplates directory instead. Editor templates are really useful for replacing your stock DateTime edit controls with a jQuery UI DateTime picker. This is a task which many of us have lived through countless times before.

Also remember that templating can be used with complex data types as well. In WeBlog, we are using display and editor templates for blog posts and various other object types. It has really helped to centralize code and increase maintainability.

Tags: , ,

Comments

David United States, on 5/2/2010 10:49:11 PM Said:

David

Now that's insane! I just wrote that bloody extension method in this new MVC2 app I'm on now.. Thanks!!

Smile

DotNetShoutout , on 5/3/2010 8:51:43 AM Said:

trackback

Display and Editor Templates in ASP.NET MVC 2

Thank you for submitting this cool story - Trackback from DotNetShoutout

DotNetKicks.com , on 5/3/2010 8:54:06 AM Said:

trackback

Display and Editor Templates in ASP.NET MVC 2

You've been kicked (a good thing) - Trackback from DotNetKicks.com

topsy.com , on 5/3/2010 9:58:08 AM Said:

pingback

Pingback from topsy.com

Twitter Trackbacks for
        
        Code Capers | Display and Editor Templates in ASP.NET MVC 2
        [codecapers.com]
        on Topsy.com

endyear2012.com , on 5/5/2010 2:18:54 AM Said:

pingback

Pingback from endyear2012.com

car insurance cheap quote «  End Year 2012

Felix Netherlands, on 5/7/2010 2:47:29 AM Said:

Felix

Hi, these templates look great. I am wondering though if I can somehow diffentiate what editor or display template to use on different occasions or views. For example, I may want to edit and display a full date (including time) on some views, but only the date part on others. How can that be done?

mikeceranski United States, on 5/7/2010 8:03:09 AM Said:

mikeceranski

Felix,
    The EditorFor and DisplayFor method have overloaded versions which accept a template name. So you could make a partial view named "FullDate.ascx". Then you would call <%= Html.EditorFor( m => m.Date, "FullDate" ) %> to use the template.
Thanks,
   Mike


165.1fh.org , on 5/20/2010 1:30:18 PM Said:

pingback

Pingback from 165.1fh.org

Honda Prowler, Trident 15 Ocean Kayak Prowler

designer handbags United States, on 5/23/2010 10:16:01 PM Said:

designer handbags

For example, I may want to edit and display a full date (including time) on some views, but only the date part on others. How can that be done?

Comments are closed