C# – How to change the default input format on the DateTime model binder in .Net MVC

asp.net-mvcc

I have a fairly standard .Net MVC Controller method:

public ActionResult Add(Customer cust) {  
  //do something...  
  return View();
}

Where Customer is something like:

public class Customer {
  public DateTime DateOfBirth { get; set; }
  //more stuff...
}

And a page containing:

<div><%= Html.TextBox("DateOfBirth") %></div>

The problem is my site is located on a US server so the cust.DateOfBirth is parsed in the US format MM/dd/yyyy. However, I want the users to enter their date of birth in the UK format dd/MM/yyyy.

Can I change the default input format on the DateTime ModelBinder or do I have to create my own custom ModelBinder?

Best Answer

You can change the culture in the web.config file or at the page level. If you only want to change the date format and not the other aspects of the culture, though, that may require that you modify the current culture's DateTimeFormat via code in global.asax or a common base controller and set it to the DateTimeFormat for "en-GB".

Reference

To set the UI culture and culture for all pages, add a globalization section to the Web.config file, and then set the uiculture and culture attributes, as shown in the following example:

<globalization uiCulture="en" culture="en-GB" />

To set the UI culture and culture for an individual page, set the Culture and UICulture attributes of the @ Page directive, as shown in the following example:

<%@ Page UICulture="en" Culture="en-GB" %>

To have ASP.NET set the UI culture and culture to the first language that is specified in the current browser settings, set UICulture and Culture to auto. Alternatively, you can set this value to auto:culture_info_name, where culture_info_name is a culture name. For a list of culture names, see CultureInfo. You can make this setting either in the @ Page directive or Web.config file.

Alternative:

 CultureInfo.CurrentUICulture.DateTimeFormat
     = CultureInfo.CurrentCulture.DateTimeFormat
     = new CultureInfo( "en-GB", false ).DateTimeFormat;