How to format the value in a strongy typed view when using ASP.Net MVC's Html.TextBoxFor

Paul Speranza picture Paul Speranza · Jan 18, 2010 · Viewed 24.5k times · Source

I am trying to format a date rendered by ASP.Net MVC's TextBoxFor using the value of a strongly typed view. The date is nullable so if it is null I want to see a blank value, otherwise I want to see it in the format MM/dd/yyyy.

<%= Html.TextBoxFor(model => model.BirthDate, new { style = "width: 75px;" })%>

Thanks,
Paul Speranza

Answer

David Glenn picture David Glenn · Jan 15, 2011

You can keep the strong typing by using a custom editor template and Html.EditorFor() instead of Html.TextBoxFor().

Create a new EditorTemplates folder in your /Views/Shared folder and add a new MVC 2 View User Control named DateTime.ascx. Add the following

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%= Html.TextBox("", (Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : string.Empty)) %>

Then in your view use

<%= Html.EditorFor(model => model.BirthDate)%></p>

Don't worry about the "", the naming will still work correctly.

If you are displaying the DateTime in a different culture format to the default application culture then you will need to change the culture information or alternatively create a custom model binder in order for the model binding to work when posting back the DateTime.