asp.Net   发布时间:2022-04-04  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在ASP.NET MVC4中自定义错误消息MVC的无效DateTime大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
无法使用我的模型中的数据注释指定验证datetiR_402_11845@e输入值的错误消息。我真的想使用适当的datetiR_402_11845@e验证器(而不是正则表达式等)。
[DataType(DataType.datetiR_402_11845@e,Errormessage = "A valid Date or Date and Time must be entered eg. January 1,2014 12:00AM")]
public datetiR_402_11845@e 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(datetiR_402_11845@E),new CustomModelBinder<datetiR_402_11845@e>());

大佬总结

以上是大佬教程为你收集整理的在ASP.NET MVC4中自定义错误消息MVC的无效DateTime全部内容,希望文章能够帮你解决在ASP.NET MVC4中自定义错误消息MVC的无效DateTime所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。