1

I'm trying to display a date. Sample of my viewmodel code is below:

[Display(Name = "Date of birth")]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date, ErrorMessage = "Enter correct date (e.g. 23.05.1980)")]
public DateTime CustomerBirthday { get; set; }

Everything is OK with displaying. But when I want to submit a form, it doesn't pass a validation if first number is greater than 12, because it expects date in format MM.dd.yyyy not dd.MM.yyyy. How can I force model binder to use my DateTime pattern (dd.MM.yyyy) and ignore culture settings.

2 Answers2

1

How can I force model binder to use my DateTime pattern (dd.MM.yyyy) and ignore culture settings.

You could write a custom model binder that will take into account the format you specified in the DisplayFormat attribute: https://stackoverflow.com/a/7836093/29407

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

The DefaultModelBinder uses the culture settings of the server for form data. So I can say the server use "en-US" culture but with a different date format.

You can do something like this in the Application_BeginRequest and you are done!

protected void Application_BeginRequest()
{
    CultureInfo info = new CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.ToString());
    info.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy";
    System.Threading.Thread.CurrentThread.CurrentCulture = info;
}
VJAI
  • 32,167
  • 23
  • 102
  • 164