在asp.net mvc 4中格式化日期时间

amb*_*amb 56 asp.net-mvc datetime-format asp.net-mvc-4

如何在asp.net mvc 4中强制使用datetime格式?在显示模式下,它显示我想要,但在编辑模型中它没有.我使用displayfor和editorfor和applyformatineditmode = true with dataformatstring ="{0:dd/MM/yyyy}"我尝试过:

  • web.config(两者都是)的全球化与我的文化和uiculture.
  • 在application_start()中修改文化和养殖
  • 用于日期时间的自定义模型

我不知道如何强制它,我需要输入日期为dd/MM/yyyy而不是默认值.

更多信息:我的viewmodel是这样的

    [DisplayName("date of birth")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? Birth { get; set; }
Run Code Online (Sandbox Code Playgroud)

在视图中我使用,@Html.DisplayFor(m=>m.Birth)但这按预期工作(我看到格式)并输入我使用的日期,@Html.EditorFor(m=>m.Birth)但如果我尝试输入像13/12/2000这样的东西失败,错误,它不是一个有效的日期(12/13/2000和2000/12/13按预期工作但我需要dd/MM/yyyy).

在application_start()中调用自定义模型绑定器b/c我不知道在哪里.

使用<globalization/>我尝试过culture="ro-RO", uiCulture="ro"和其他文化相比,我会给你dd/MM/yyyy.我也尝试在application_start()中基于每个线程设置它(这里有很多例子,关于如何做到这一点)


对于所有会读到这个问题的人来说:只要我没有客户验证,Darin Dimitrov的答案就会起作用.另一种方法是使用自定义验证,包括客户端验证.我很高兴在重新创建整个应用程序之前发现了这一点.

Dar*_*rov 102

啊,现在很清楚了.您似乎在绑定值时遇到问题.不在视图上显示它.实际上,这是默认模型绑定器的错误.您可以编写并使用自定义的,将考虑[DisplayFormat]模型上的属性.我在这里说明了这样一个自定义模型绑定器:https://stackoverflow.com/a/7836093/29407


显然有些问题仍然存在.这是我的完整设置在ASP.NET MVC 3和4 RC上完美运行.

模型:

public class MyViewModel
{
    [DisplayName("date of birth")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? Birth { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel
        {
            Birth = DateTime.Now
        });
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}
Run Code Online (Sandbox Code Playgroud)

视图:

@model MyViewModel

@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.Birth)
    @Html.EditorFor(x => x.Birth)
    @Html.ValidationMessageFor(x => x.Birth)
    <button type="submit">OK</button>
}
Run Code Online (Sandbox Code Playgroud)

在以下位置注册自定义模型活页夹Application_Start:

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

而自定义模型绑定器本身:

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)

现在,无论您在web.config(<globalization>元素)或当前线程文化中设置了什么文化,自定义模型绑定器将DisplayFormat在解析可为空的日期时使用属性的日期格式.