[ Log On ]

Welcome to TexasJetter

This site’s purpose is to share tips, tricks, and techniques I have learned in my day to day workings as a developer. Topics you may find here will cover mostly Microsoft technologies, such as ASP.NET, Web Forms, AJAX, MVC, Silverlight, and WPF. Along the way you may find a little jQuery and javascript thrown in to keep things dynamic.

This site also serves as a repository of how items of interest have been done, or might be done when I have the future need. I know in my travels across the Internet I come across a wide range of interesting topics, some of which I may not have a use for at the time but want to keep in mind should I need them in the future. Occasionally a topic will inspire me enough to work through the technique, even though I am not currently using it. In that case it will show up here.
- Enjoy

Improved MVC Date Template

Friday, March 16, 2012

This will be a short and simple post dealing with an improvement on the traditional display and editor templates normally found for MVC date display. If you are not familiar with the issue, normally a DateTime field will display the full information, including the time. Commonly this is not the desired display, we only want the date part. While you can format the display on each view, that becomes cumbersome, and it is easy to miss one. MVC has a great solution for that, called DisplayTemplates. Located in the \Views\Shared\DisplayTemplates folder they will apply to that data type site wide. So creating a DateTime.cshtml file here will be used for the display anytime the @Html.DisplayFor helper is used (the same is applied for the @Html.EditorFor and the EditorTemplates folder).

Commonly the contents of the DateTime.cshtml file is simple:

@model System.DateTime @string.Format("{0:d}", Model)

This partial view simply formats the DateTime values using the ShortDate pattern. Simply create the file, and you are ready to do… But what if the field is initialized, but has no value? I recently had a case where the field was not null, but contained the default date of 01/01/0001. Obviously this was not the desired display. Continue on to find out the simply solution.

About Me

Jeff Etter

My name is Jeff Etter and I am currently a developer for EPS-Software, offering a wide range of consulting services focusing on development, architecture, and project management located in Spring,TX. More...