如何在.Net MVC中更改DateTime模型绑定器上的默认输入格式?

我有一个相当标准的.Net MVC控制器方法:

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

客户是这样的:

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

还有一个页面包含:

 

问题是我的网站位于美国服务器上,因此cust.DateOfBirth以美国格式MM / dd / yyyy进行解析。 但是,我希望用户以英国格式dd / MM / yyyy输入他们的出生日期。

我可以更改DateTime ModelBinder上的默认输入格式,还是必须创建自己的自定义ModelBinder?

您可以在web.config文件或页面级别更改区域性。 但是,如果您只想更改日期格式而不是文化的其他方面,则可能需要通过global.asax中的代码或公共基本控制器修改当前区域性的DateTimeFormat,并将其设置为DateEFormat for“en -GB”。

参考

要为所有页面设置UI文化和文化,请将全球化部分添加到Web.config文件,然后设置uiculture和culture属性,如以下示例所示:

要为单个页面设置UI文化和文化,请设置@ Page指令的Culture和UICulture属性,如以下示例所示:

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

要让ASP.NET将UI文化和文化设置为当前浏览器设置中指定的第一种语言,请将UICulture和Culture设置为auto。 或者,您可以将此值设置为auto:culture_info_name,其中culture_info_name是区域性名称。 有关文化名称的列表,请参阅CultureInfo。 您可以在@ Page指令或Web.config文件中进行此设置。

替代方案:

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

您可以更改不同快捷方式的含义。 在您的情况下,它将是短日期模式或“d”。 如果您通常喜欢en-US文化,但只需要更改短日期时间的日期时间模式,则可以将其添加到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; } 

第一个数组是支持的日期时间格式,第二个字符是您要替换的模式。