1

我正在尝试显示日期。我的视图模型代码示例如下:

[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) 并忽略文化设置。

4

2 回答 2

1

如何强制模型绑定器使用我的 DateTime 模式 (dd.MM.yyyy) 并忽略文化设置。

您可以编写一个自定义模型绑定器,它将考虑您在 DisplayFormat 属性中指定的格式:https ://stackoverflow.com/a/7836093/29407

于 2012-06-21T14:20:40.843 回答
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;
}
于 2012-06-21T15:32:08.377 回答