Asp.net-MVC 现在允许隐式绑定(bind) DateTime 对象。我有一个类似的行动
public ActionResult DoSomething(DateTime startDate)
{
...
}
这成功地将 ajax 调用中的字符串转换为 DateTime。但是,我们使用日期格式 dd/MM/yyyy; MVC 正在转换为 MM/dd/yyyy。 例如,使用字符串“09/02/2009”提交对操作的调用会导致 DateTime 为“02/09/2009 00:00:00”,或者在我们的本地设置中为 9 月 2 日。
我不想为了日期格式而推出自己的模型 Binder 。但是,如果 MVC 能够为我执行此操作,则似乎不必更改操作以接受字符串然后使用 DateTime.Parse。
有什么方法可以改变默认模型绑定(bind)器中用于 DateTime 的日期格式吗?默认模型绑定(bind)器不应该使用您的本地化设置吗?
最佳答案
我刚刚通过更详尽的谷歌搜索找到了答案:
Melvyn Harbour 详细解释了 MVC 为何以这种方式处理日期,以及如何在必要时覆盖它:
http://weblogs.asp.net/melvynharbour/archive/2008/11/21/mvc-modelbinder-and-localization.aspx
When looking for the value to parse, the framework looks in a specific order namely:
- RouteData (not shown above)
- URI query string
- Request form
Only the last of these will be culture aware however. There is a very good reason for this, from a localization perspective. Imagine that I have written a web application showing airline flight information that I publish online. I look up flights on a certain date by clicking on a link for that day (perhaps something like http://www.melsflighttimes.com/Flights/2008-11-21), and then want to email that link to my colleague in the US. The only way that we could guarantee that we will both be looking at the same page of data is if the InvariantCulture is used. By contrast, if I'm using a form to book my flight, everything is happening in a tight cycle. The data can respect the CurrentCulture when it is written to the form, and so needs to respect it when coming back from the form.
https://stackoverflow.com/questions/528545/