我的应用程序在 web.config 中设置了 pt-BR 区域性(日期为 dd-mm-yyyy):
<globalization enableClientBasedCulture="false" requestEncoding="utf-8" responseEncoding="utf-8" fileEncoding="iso-8859-15" responseHeaderEncoding="utf-8" resourceProviderFactoryType="string" enableBestFitResponseEncoding="true" culture="pt-BR" uiCulture="pt-BR" />
在我的系统上创建的所有日期时间都是正确的格式,但我创建了一个像这样的控制器方法:
public ActionResult Test(DateTime date)
{
}
当日期采用 portuguese-br 格式时,直接在浏览器中调用该方法会传递 null,如下所示:
mysite/Test/?date=19/01/2012 => date = null in my controller
mysite/Test/?date=01/01/2012 => date is fine, but in US format (mm-dd-yyyy)
我该如何解决这个问题,以接受我的日期格式?
默认模型绑定器有一个不容易了解的陷阱,但一旦你知道了它,你就不会再犯同样的错误:
由于您使用 GET 请求并将日期作为查询字符串参数传递,因此在 url 中发送时应使用不变区域性格式对其进行格式化。将日期格式化为查询字符串参数的正确方法是yyyy-MM-dd
.
你可以看看以下博客文章 http://weblogs.asp.net/melvynharbour/archive/2008/11/21/mvc-modelbinder-and-localization.aspx其中涉及更多细节。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)