– Format Date On Binding (ASP.NET MVC)

In my MVC app I have a view that looks like this:

<label>Due Date</label>

I am using a ModelBinder to bind the post to my model (the due property is of DateTime type). The problem is when I put "01/01/2009" into the textbox, and the post does not validate (due to other data being input incorrectly). The binder repopulates it with the date and time "01/01/2009 00:00:00".

Is there any way to tell the binder to format the date correctly (i.e. ToShortDateString())?

Best Answer

I just came across this very simple and elegant solution, available in MVC 2:

Basically if you are using MVC 2.0, use the following in your view.

 <%=Html.LabelFor(m => m.due) %>
 <%=Html.EditorFor(m => m.due)%>

then create a partial view in /Views/Shared/EditorTemplates, called DateTime.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%=Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "datePicker" }) %>

When the EditorFor<> is called it will find a matching Editor Template.