【问题标题】:Why am I getting dateFormat validation error为什么我收到 dateFormat 验证错误
【发布时间】:2013-11-13 15:16:13
【问题描述】:

我正在使用带有 Razor 的 ASP.NET MVC 4。我收到验证消息(假设我的文本框中有 20.10.2013):

The field MyNullableDateField must be a date

我的型号代码:

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

我的剃须刀:

@Html.EditorFor(m => m.MyNullableDateField, new { @class = "date" })

我的编辑器模板:

@model DateTime?
@Html.TextBox(string.Empty, (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "date" })

为什么会出现这样的错误?

【问题讨论】:

  • 重复,属于ASP.NET MVC3 - DateTime format。简而言之:因为DisplayFormat 被默认模型绑定器忽略。创建您自己的模型绑定器。

标签: asp.net-mvc-3 asp.net-mvc-4 razor mvc-editor-templates


【解决方案1】:

安德烈,

显示格式主要供您在视图上使用的 Html 帮助器使用。

您需要的是(正如@CodeCaster 正确提到的)是 DateTime 类型的自定义模型绑定器。自定义模型绑定器可以按类型注册,因此每当 MVC 运行时看到相同类型的控制器操作的参数时,它会调用自定义模型绑定器以正确解释发布的值并创建类型,

以下是 DateTime 的示例自定义模型绑定器类型

public class DateTimeModelBinder : DefaultModelBinder
{
    private string _customFormat;

    public DateTimeModelBinder(string customFormat)
    {
        _customFormat = customFormat;
    }

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
    // use correct fromatting to format the value
        return DateTime.ParseExact(value.AttemptedValue, _customFormat, CultureInfo.InvariantCulture);
    }
}

现在您必须告诉 MVC 将您的新模型绑定器用于 DateTime。您可以通过在 Application_Start 注册新的模型绑定器来做到这一点

protected void Application_Start()
{
    //tell MVC all about your new custom model binder
    var binder = new DateTimeModelBinder("dd.MM.yyyy");
    ModelBinders.Binders.Add(typeof(DateTime), binder);
    ModelBinders.Binders.Add(typeof(DateTime?), binder);
}

感谢这篇关于日期时间自定义模型绑定的优秀文章 (http://blog.greatrexpectations.com/2013/01/10/custom-date-formats-and-the-mvc-model-binder/)

希望这有助于您开始正确的部分

【讨论】:

    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    相关资源
    最近更新 更多