asp.net-mvc - 日期格式不正确的 MVC DateTime 绑定(bind)

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:

  1. RouteData (not shown above)
  2. URI query string
  3. 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/

相关文章:

javascript - 如果一千或更多,则将数字格式化为 2.5K,否则为 900

visual-studio - 在 Visual Studio 中关闭自动格式化

r - 如何在R中将数字格式化为百分比?

java - Java中的双十进制格式

java - 如何在java中将当前日期转换为字符串?

windows - 将换行格式从 Mac 转换为 Windows

java - Java中的JPanel填充

python - 转换为二进制并保留前导零

python - 如何在文件中写入 YAML 格式的数据?

sql - 为什么我应该将我的 SQL 关键字大写?有充分的理由吗?