How to change the default input format on a DateTime model binding in .Net MVC?

I have a pretty standard .Net MVC Controller method:

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

Where the 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 that my site is located on an American server, so cust.DateOfBirth is parsed in US format MM / dd / yyyy. However, I want users to enter the date of birth in the British dd / MM / yyyy format.

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

+4
c # asp.net-mvc
Jul 14 '09 at 12:05
source share
2 answers

You can change the culture in the web.config file or at the page level. However, if you want to change the date format and not other aspects of the culture, this may require changing the current DateTimeFormat culture using the code in global.asax or a common base controller and setting it to DateTimeFormat for "en -GB".

Link

To customize the culture and culture of the user interface for all pages, add the globalization section to the Web.config file, and then set the maturity and culture attributes, as shown in the following example:

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

To customize the culture and culture of the user interface for a single page, set the Culture and UICulture attributes on the directive page, as shown below Example:

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

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

Alternative:

  CultureInfo.CurrentUICulture.DateTimeFormat = CultureInfo.CurrentCulture.DateTimeFormat = new CultureInfo( "en-GB", false ).DateTimeFormat; 
+4
Jul 14 '09 at 12:21
source share

You can change the meaning of various shortcut templates. In your case, it will be a short date pattern or "d". If you like the en-US culture, you just need to change the date time pattern to a short time, you can add this to Global.asax .

 protected void Application_BeginRequest(Object sender, EventArgs e) { CultureInfo ci = new CultureInfo("en-US"); ci.DateTimeFormat.SetAllDateTimePatterns( new string[] { "dd/MM/yyyy" }, 'd' ); System.Threading.Thread.CurrentThread.CurrentCulture = ci; System.Threading.Thread.CurrentThread.CurrentUICulture = ci; } 

The first array is the supported date formats, the second character is the template you would like to replace.

+2
Jul 14 '09 at 12:32
source share



All Articles