gpt4 book ai didi

asp.net-mvc-3 - 通过 URL 将 DateTime 传递到 Controller 导致 ASP .NET MVC 3 中出现错误(区域性)

转载 作者:行者123 更新时间:2023-12-02 07:43:42 26 4
gpt4 key购买 nike

我的应用程序在 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" />

在我的系统上创建的所有日期时间都是正确的格式,但我创建了一个像这样的 Controller 方法:

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)

我该如何解决这个问题,以接受我的日期格式?

最佳答案

默认模型绑定(bind)器有一个不容易了解的陷阱,但一旦了解它,就不会再犯同样的错误:

  • 当您使用 POST 请求时,默认模型绑定(bind)器会使用您的区域性设置来解析日期。

  • 当您使用 GET 请求时,默认模型绑定(bind)器使用 CultureInfo.InvariantCulture 解析日期并忽略您当前的区域性设置。

由于您使用 GET 请求并将日期作为查询字符串参数传递,因此在 URL 中发送时应使用不变区域性格式对其进行格式化。将日期格式化为查询字符串参数的正确方法是 yyyy-MM-dd

您可以查看following blog post其中涉及更多细节。

关于asp.net-mvc-3 - 通过 URL 将 DateTime 传递到 Controller 导致 ASP .NET MVC 3 中出现错误(区域性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8910482/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com