ASP.NET MVC3 - DateTime格式

šlj*_*ker 28 datetime asp.net-mvc-3

我正在使用ASP.NET MVC 3.
我的ViewModel看起来像这样:

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

在视图中,我有这样的事情:

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

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

任何帮助将不胜感激!

Dar*_*rov 43

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

<globalization culture="...." uiCulture="...." />
Run Code Online (Sandbox Code Playgroud)

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


更新:

根据您在评论部分中的要求,您希望保留应用程序的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

您将在Application_Start以下地址注册:

ModelBinders.Binders.Add(typeof(DateTime), new MyDateTimeModelBinder());
Run Code Online (Sandbox Code Playgroud)


VJA*_*JAI 10

根据你的评论,我看到你想要的只是一个英语潮流,但有不同的日期格式(纠正我,如果我错了).

事实是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;
}
Run Code Online (Sandbox Code Playgroud)

Web.Config中

<globalization culture="en-US" />
Run Code Online (Sandbox Code Playgroud)