Customize the Error Message MVC for an invalid DateTime in ASP.NET MVC4

后端 未结 5 1293
不知归路
不知归路 2020-12-23 15:20

I am having trouble specifying the error message for the validation of a DateTime input value using data annotations in my model. I would really like to use the proper DateT

5条回答
  •  孤独总比滥情好
    2020-12-23 15:33

    I have one dirty solution.

    Create custom model binder:

    public class CustomModelBinder : 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);
        }
    }
    

    And then in Global.asax.cs:

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

提交回复
热议问题