【问题标题】:MVC DateTime format can not be parsedMVC DateTime 格式无法解析
【发布时间】:2013-06-27 19:51:33
【问题描述】:

在最近从 MVC3 升级到 4 之后,我遇到了一些日期时间问题。我显示这样的日期属性:

<%: Html.DisplayFor(m => m.InvoiceDate, "datetime")%>&nbsp; 

"datetime" 是一个显示模板,如下所示:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime?>" %>
<%: Model.HasValue ? Model.Value.ToString("dd/MM/yy", null) : ""%>

在我的 global.asax 文件中,我注册了以下模型绑定器:

 ModelBinders.Binders.Add(typeof(DateTime), new SMEEDI.Portal.Common.DateTimeModelBinder());
 ModelBinders.Binders.Add(typeof(DateTime?), new SMEEDI.Portal.Common.DateTimeModelBinder());

看起来像这样:

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        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
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-NZ");
            return DateTime.Parse(date, CultureInfo.CurrentCulture.DateTimeFormat);
        }

        catch (Exception)
        {

            bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format("\"{0}\" is invalid.", bindingContext.ModelName));

            return null;

        }

日期时间在视图中正确显示,但是当提交表单时,日期返回如下:“7/20/2013 12:00:00 AM”并且 DateTimeModelBinder 抛出格式异常:String was not识别为有效的日期时间。 (在新西兰,月份和日期是相反的)。

为什么它会以这种格式返回?为什么它不能解析它?为什么升级到 MVC 4 时会发生这种情况?我怎样才能让它以 NZ 格式返回?我是否应该在解析时不指定文化,这是以前的 MVC 版本中可能需要的吗?

【问题讨论】:

    标签: asp.net-mvc datetime format display-templates asp.net-mvc-migration


    【解决方案1】:

    这是一个棘手的领域。涉及的因素很多。

    其中一个原因可能是网络浏览器设置为美国英语。

    如何设置线程的文化信息。您可以使用Thread.CurrentThread.CurrentCulture 或在网络配置中&lt;globalization enableClientBasedCulture="true" culture="auto:en-NZ" uiCulture="auto:en"/&gt; 进行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 2013-09-24
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多