You can automagically format dates and add a jquery datepicker to the input box for all DateTime (and nullable DateTime) properties for your view. You just need to add a DateTime.ascx partial view to your Views/Shared/EditorTemplates folder and use the standard Html.EditorFor helper for date properties in your views. Here’s the details:

If not there already, add a folder called “EditorTemplates” to your presentation project’s Views/Shared folder. MVC will automatically look in this folder first for all EditorFor templates.

In the Views/Shared/EditorTemplates folder, add a Partial View called “DateTime”. This will create a DateTime.ascx file.

Replace the contents of that file with this:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<system.DateTime?>" %>
<%@ Import Namespace="System.Web.Mvc.Html" %>
<%: Html.TextBox("", String.Format("{0:MM/dd/yyyy}", 
(Model == DateTime.MinValue)? null : Model))%>
<script type="text/javascript">
    $(document).ready(function () {
        $("#<%: ViewData.ModelMetadata.PropertyName %>").datepicker({
            changeMonth: true,
            changeYear: true,
            dateFormat: 'mm/dd/yy',
            showButtonPanel: true,
            gotoCurrent: true

From now on, as long as the datatype of the property is DateTime or DateTime?, Html.EditorFor will automagically format the date and add a jquery datepicker to the input box:

<%: Html.EditorFor(x => x.PostedDate) %>

NOTE: the example is referencing a root property, not a nested property. The DateTime.ascx control won’t work with a view model that has another model object as a property, like x=>x.MyNestedModel.PostedDate.

« »