Create user friendly date fields with ASP.NET MVC EditorTemplates &amp

added by pyccki
4/19/2011 1:17:57 PM

0 Kicks, 145 Views

Today's web sites need to be user friendly, interactive, and responsive. The date field is of particular interest because at this point in time, users pretty much expect too see nicely formatted dates on the site in general, and datepicker/calendar widgets to interact with when editing date fields. The best way to do this, of course, is with client side script; and when working in ASP.NET MVC, those scripts can work seamlessly with templates. What are MVC EditorTemplates & DisplayTemplates? Editor & Display templates behave a lot like partial views, since they're just .cshtml/.ascx files (so they technically are partial views), and they produce output inside of regular views, just like partial views. However, there are some key differences that distinguish templates from views: Templates render at an application wide scope, automatically. When you use partial views, you must call them from another view using helper syntax, e.g., @Html.Partial("_PartialViewName"). Templates render themselves only for the specific data types that they're setup to handle, e.g., DateTime, decimal or int, throughout the entire application. If you setup an EditorTemplate to render output for a particular data type, it will do so for every single field of that type in the application while partial views aren't tied to any particular data type. A DisplayTemplate renders itself only when its specific data type needs to display in an Index, Details, Delete, or custom view. An EditorTemplate renders itself only when its specific data type is in edit mode and while in Edit mode. A benefit of using Editor and DisplayTemplates is that you don't have to add repetitive code into views individually. More importantly you won't find yourself adding code to work with each field individually, as that creates code that's not DRY and harder to maintain. Just add your Html Helpers, widgets, & script to the templates directly and the Razor/ASPX view engine will take over to produce output based on those data types in templates.