ASP.NET MVC3 - 日期时间格式
我正在使用 ASP.NET MVC 3。
我的 ViewModel 看起来像这样:
public class Foo
{
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
...
}
在视图中,我有这样的内容:
<div class="editor-field">
@Html.EditorFor(model => model.StartDate)
<br />
@Html.ValidationMessageFor(model => model.StartDate)
</div>
StartDate 以正确的格式显示,但是当我将其值更改为 19.11.2011 并提交表单时,我收到以下错误消息:“值 '19.11. 2011' 对于开始日期无效。”
任何帮助将不胜感激!
I'm using ASP.NET MVC 3.
My ViewModel looks like this:
public class Foo
{
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
...
}
In view, I have something like this:
<div class="editor-field">
@Html.EditorFor(model => model.StartDate)
<br />
@Html.ValidationMessageFor(model => model.StartDate)
</div>
StartDate is displayed in correct format, but when I change it's value to 19.11.2011 and submit the form, I get the following error message: "The value '19.11.2011' is not valid for StartDate."
Any help would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要在 web.config 文件的全球化元素中设置正确的区域性,其中
dd.MM.yyyy
是有效的日期时间格式:例如,这是德语的默认格式:
de -DE
。更新:
根据您在评论部分的要求,您希望保留应用程序的美国文化,但仍使用不同的日期格式。这可以通过编写自定义模型绑定器来实现:
您将在
Application_Start
中注册该模型绑定器:You need to set the proper culture in the globalization element of your web.config file for which
dd.MM.yyyy
is a valid datetime format:For example that's the default format in german:
de-DE
.UPDATE:
According to your requirement in the comments section you want to keep en-US culture of the application but still use a different formats for the dates. This could be achieved by writing a custom model binder:
which you will register in
Application_Start
:根据您的评论,我看到您想要的只是当前的英语,但日期格式不同(如果我错了,请纠正我)。
事实上,
DefaultModelBinder
使用服务器的区域性设置来处理表单数据。所以我可以说服务器使用“en-US”文化,但日期格式不同。您可以在
Application_BeginRequest
中执行类似的操作,然后就完成了!Web.Config
Based upon your comment I see all you want is an english current but with a different date format (Correct me if I'm wrong).
The fact is the
DefaultModelBinder
uses the culture settings of the server for form data. So I can say the server use "en-US" culture but with a different date format.You can do something like this in the
Application_BeginRequest
and you are done!Web.Config
将以下代码添加到 global.asax.cs 文件
并将以下代码添加到
下的 web.configAdded this below code to global.asax.cs file
And added the below to web.config under
<system.web>