【问题标题】:ASP.NET MVC3 - DateTime formatASP.NET MVC3 - 日期时间格式
【发布时间】:2011-10-20 12:00:02
【问题描述】:

我正在使用 ASP.NET MVC 3。
我的 ViewModel 如下所示:

public class Foo
{
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
    public DateTime StartDate { get; set; }
    ...
}

在看来,我有这样的事情:

<div class="editor-field">
    @Html.EditorFor(model => model.StartDate)
    <br />
    @Html.ValidationMessageFor(model => model.StartDate)
</div>

StartDate 以正确的格式显示,但是当我将其值更改为 19.11.2011 并提交表单时,我收到以下错误消息:“值 '19.11.2011' 对于 StartDate 无效。”

任何帮助将不胜感激!

【问题讨论】:

    标签: asp.net-mvc-3 datetime


    【解决方案1】:

    您需要在 web.config 文件的全球化元素中设置正确的文化,dd.MM.yyyy 是有效的日期时间格式:

    <globalization culture="...." uiCulture="...." />
    

    例如,这是德语的默认格式:de-DE


    更新:

    根据您在 cmets 部分中的要求,您希望保留应用程序的 en-US 文化,但仍使用不同的日期格式。这可以通过编写自定义模型绑定器来实现:

    using System.Web.Mvc;
    public class MyDateTimeModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
    
            if (!string.IsNullOrEmpty(displayFormat) && value != null)
            {
                DateTime date;
                displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
                // use the format specified in the DisplayFormat attribute to parse the date
                if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
                {
                    return date;
                }
                else
                {
                    bindingContext.ModelState.AddModelError(
                        bindingContext.ModelName, 
                        string.Format("{0} is an invalid date format", value.AttemptedValue)
                    );
                }
            }
    
            return base.BindModel(controllerContext, bindingContext);
        }
    }
    

    你将在Application_Start注册:

    ModelBinders.Binders.Add(typeof(DateTime), new MyDateTimeModelBinder());
    

    【讨论】:

    • 但我不想使用具有不同日期时间格式的英语文化。有什么解决办法吗?
    • @šljaker,是的。您必须编写自定义模型绑定器并使用您喜欢的格式手动解析日期参数。
    • 全球化标签是 标签的子标签。
    • 嗨,达林,我有一个问题,dd/MM/yyyy 格式在本地机器上工作正常,但我们的网站托管在另一个国家,它需要MM/dd/yyyy 格式,否则会显示验证错误The field BeginDate must be a date.,我怎样才能让服务器接受dd/MM/yyyy 格式,全球化会起作用吗?我可以在视图页面而不是 web.config 中添加全球化吗?
    • 我可以完全关闭日期验证吗?
    【解决方案2】:

    根据您的评论,我看到您想要的只是英文电流,但日期格式不同(如果我错了,请纠正我)。

    事实上DefaultModelBinder 使用服务器的文化设置来处理表单数据。所以我可以说服务器使用“en-US”文化,但日期格式不同。

    您可以在Application_BeginRequest 中执行类似的操作,然后您就完成了!

    protected void Application_BeginRequest()
    {
        CultureInfo info = new CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.ToString());
        info.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy";
        System.Threading.Thread.CurrentThread.CurrentCulture = info;
    }
    

    Web.Config

    <globalization culture="en-US" />
    

    【讨论】:

      【解决方案3】:

      将以下代码添加到 global.asax.cs 文件

      protected void Application_BeginRequest()  
      {        
          CultureInfo info = new CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.ToString());     
          info.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy";
          System.Threading.Thread.CurrentThread.CurrentCulture = info;     
      }
      

      并将以下内容添加到&lt;system.web&gt;下的web.config

      <globalization culture="en-US">;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-02
        • 2012-11-28
        • 1970-01-01
        • 2023-04-06
        • 1970-01-01
        • 2013-11-09
        • 1970-01-01
        相关资源
        最近更新 更多