Question

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?

Was it helpful?

Solution

Do this:

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

OTHER TIPS

In fact I believe that the problem here is related to the fact that the DefaultModelBinder does not deal with datetimes in a proper way (meaning that we cannot bind a front-end field to a DateTime partial, like we used to do in others [cough CastleMonorail cough] MVC frameworks).

I've created a custom model binder exactly to deal with that issue. But Scott Hanselman has done something similar here, so I guess you can just use his solution.

Of course, you may deal with this situation through attributes, but that means that you'll need to specify that special formatting in all DateTime fields. And that will not solve another problem: sometimes we need to have one field for the date part and another for the time part only in the front-end, and keep a single datetime field in the backend. This model binder solution allows exactly that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top