Display and Editor Templates in ASP.NET MVC 2

added by mceranski
5/3/2010 7:53:54 AM

0 Kicks, 220 Views

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. Read the full story at codecapers: http://www.codecapers.com/post/Display-and-Editor-Templates-in-ASPNET-MVC-2.aspx