2012-06-21 36 views
1

我想顯示一個日期。我的viewmodel代碼示例如下:格式在ASP.NET MVC中的日期時間3

[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; } 

一切正常顯示。但是當我想提交一個表單時,如果第一個數字大於12,那麼它不會通過驗證,因爲它期望格式爲MM.dd.yyyy而不是dd.MM.yyyy。 如何強制模型聯編程序使用我的DateTime模式(dd.MM.yyyy)並忽略文化設置。

回答

1

我如何可以強制模型綁定使用我的DateTime模式(DD.MM.YYYY) 而忽略文化設置。

你可以寫,將考慮到你在DisplayFormat屬性指定的格式自定義模型綁定:https://stackoverflow.com/a/7836093/29407

1

DefaultModelBinder使用服務器的文化設置表單數據。所以我可以說服務器使用「en-US」文化,但使用不同的日期格式。

你可以在Application_BeginRequest這樣做,你就完成了!

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; 
}