apolka
apolka

Reputation: 1721

How to specify date format for model binding?

I hope the question is easy, but I am searching around for more than an hour and I just do not find the answer. So I have a asp.net mvc 2 application and one of the forms contains a date textbox with a jquery datepicker. I have set in the datepicker the date format to be dd.mm.yyyy. My problem is that on the model binding this date is interpreted as mm.dd.yyyy, so by the time the model reaches my action method the DateTime attribute of the model is not correct (day and month is reversed, if it is not possible to reverse it client side validation does not let me save the item). I do not want to change culture, but I would like to specify somehow to the model binder how to interpret the date. Is it possible somehow?

Thanks a lot

Upvotes: 20

Views: 17392

Answers (2)

Steve Greatrex
Steve Greatrex

Reputation: 16009

This blog post explains how you can specify a particular date format to be used by the MVC model binder.

You will need to create a custom model binder implementation that is aware of the date format, then associate that with the DateTime type in your Global.asax.cs:

protected void Application_Start()
{
    //...
    var binder = new DateTimeModelBinder(GetCustomDateFormat());
    ModelBinders.Binders.Add(typeof(DateTime), binder);
}

Upvotes: 10

Manaf Abu.Rous
Manaf Abu.Rous

Reputation: 2417

You might find the answer to your question here

Custom DateTime model binder in Asp.net MVC

Also Scott Hanselman has talked about a DateTime custom model binder here

http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx

Although he's using the binder to split the date & time you might his post useful when creating your custom model binder.

Upvotes: 2

Related Questions