在ASP.NET MVC4中自定义错误消息MVC的无效DateTime

我无法使用我的模型中的数据注释指定验证DateTime输入值的错误消息。我真的想使用适当的DateTime验证器(而不是正则表达式等)。
[DataType(DataType.DateTime,ErrorMessage = "A valid Date or Date and Time must be entered eg. January 1,2014 12:00AM")]
public DateTime Date { get; set; }

我仍然得到认日期验证消息“字段日期必须是日期”。

我错过了什么吗?

解决方法

我有一个脏的解决方案。

创建自定义模型binder:

public class CustomModelBinder<T> : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if(value != null && !String.IsNullOrEmpty(value.AttemptedValue))
        {
            T temp = default(T);
            try
            {
                temp = ( T )TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value.AttemptedValue);
            }
            catch
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName,"A valid Date or Date and Time must be entered eg. January 1,2014 12:00AM");
                bindingContext.ModelState.SetModelValue(bindingContext.ModelName,value);
            }

            return temp;
        }
        return base.BindModel(controllerContext,bindingContext);
    }
}

然后在Global.asax.cs中:

protected void Application_Start()
{
    //...
    ModelBinders.Binders.Add(typeof(DateTime),new CustomModelBinder<DateTime>());

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...