【问题标题】:DateTime that comes from a GET request uses different format than the one that comes from POST来自 GET 请求的 DateTime 使用不同于来自 POST 的格式
【发布时间】:2010-11-30 12:33:00
【问题描述】:

来自 POST 的 DateTime 绑定正确(根据我电脑的格式)

但是来自 GET 的 DateTime 值没有正确绑定,它使用了不同的格式

my format is dd.MM.yyyy, in GET it uses MM.dd.yyyy instead

I don't have this problem if I use the en-US format  (which is MM/dd/yyyy)

有人知道如何解决这个问题吗?

这是一个 mvc 错误吗? (绑定get请求时不考虑文化)

【问题讨论】:

  • 您是否从多个浏览器测试了应用程序以查看行为是否恒定?
  • @Rob,不,我没有,但我会的,谢谢建议

标签: asp.net asp.net-mvc


【解决方案1】:

不,这似乎不是错误。您可以在此处获取更多详细信息:MVC DateTime binding with incorrect date format

我一直在使用下面的 ModelBinder 来解决这个问题。

public class CurrentCultureDateTimeBinder : IModelBinder
{
    private const string PARSE_ERROR = "\"{0}\" is not a valid date";
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (valueProviderResult == null) return null;

        var date = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;

        if (String.IsNullOrEmpty(date))
            return null;

        bindingContext.ModelState.SetModelValue(bindingContext.ModelName, bindingContext.ValueProvider.GetValue(bindingContext.ModelName));

        try
        {
            return DateTime.Parse(date);
        }
        catch (Exception)
        {
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format(PARSE_ERROR, bindingContext.ModelName));
            return null;
        }
    }
}

希望对你有帮助。

【讨论】:

  • @Omu 之所以有效,是因为 DateTime.Parse(String) 使用当前线程文化(使活页夹文化感知)。相反,默认活页夹使用 CultureInfo.InvariantCulture。您可以在此处查看更多详细信息:weblogs.asp.net/melvynharbour/archive/2008/11/21/…
猜你喜欢
  • 1970-01-01
  • 2016-10-17
  • 1970-01-01
  • 2019-08-10
  • 2020-11-08
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多