Search code examples
asp.net-mvcasp.net-mvc-3datetimedata-annotationsmodelmetadata

Problem with MVC ModelMetaData attributes and formatting a Date


I am trying to figure out how to format a date using MVC3 RC2 and a model decorated with DataAnnotations.

This is my model...

public class Model
{
    [Display(Name = "Date of Birth")]
    [DisplayFormat(@DataFormatString = "MM/dd/yyyy")]
    public DateTime DateOfBirth { get; set; }
}

This is my controller...

public class IndexController : Controller
{
    public ActionResult Index()
    {
        return View( new Model() {DateOfBirth = DateTime.Now});
    }
}

This is my view...

@model MvcApplication6.Models.Model

@Html.LabelFor(m=>m.DateOfBirth)
@Html.TextBoxFor(m => m.DateOfBirth)
@Html.EditorFor(m => m.DateOfBirth)

When I run the site, for both controls, the page displays a textbox with the time included in the string, when all I want is the date (as specified by the decorated property in the model).

I used Brad Wilson's article on ModelMetaData for this pattern.

Is it obvious what I am doing wrong?


Solution

  • Do this:

    [DisplayName("Date of Birth")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime DateOfBirth { get; set; }