Close this search box.

Apply a DateTime Format in an Asp.Net MVC TextBoxFor

I use MVC4 with razor.

I ran into the problem of formating correctly a DateTime property of my model that I render in the view using a TextBoxFor MVC helper. The default formatting displays the full date with hours, minutes and seconds :

@Html.TextBoxFor(m => m.BeginDate)

displays “27/04/2012 00:00:00” in the textbox. I only needed the first part so I wanted to use the ‘d’ format.

I then tried to use DataAnnotations to impose a format to the property to display:

[DisplayFormat(DataFormatString = "{0:d}")]
        public DateTime BeginDate { get; set; }

Still, the generated textbox has the full date displayed : “27/04/2012 00:00:00”

There are actually 2 solutions to that :

1- Use DataAnnotations + EditorFor

The dataannotation DisplayFormat is actually NOT taken into account when the data is rendered with @Html.TextBoxFor helper. It applies only to the EditorFor helper.

So, keeping your dataannotation and replacing your helper by this shoud work :

@Html.EditorFor(m => m.BeginDate)

2 -Use TextBoxFor and alter the @Value parameter

If you really want your TextBoxFor, there is also a solution which I find less desirable since it tinkles with the default behavior of TextBoxFor.

You can remove the DisplayFormat data annotation and use this helper :

@Html.TextBoxFor(m => m.BeginDate, new { @Value = Model.BeginDate.ToString("d") })
This article is part of the GWB Archives. Original Author: Etienne Giust`s

Related Posts