加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 00:37:08 所属栏目:asp.Net 来源:网络整理
导读:我无法使用我的模型中的数据注释指定验证DateTime输入值的错误消息。我真的想使用适当的DateTime验证器(而不是正则表达式等)。 [DataType(DataType.DateTime,ErrorMessage = "A valid Date or Date and Time must be entered eg. January 1,2014 12:00AM")]p
我无法使用我的模型中的数据注释指定验证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>());

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读