Globally Override ASP.Net MVC Default Attribute Error Messages

风格不统一 提交于 2019-12-05 16:20:50

This might be quite late, but then here is a solution that should work based primarily on the logic behind your partial solution.

  1. Implement a custom RequiredAttribute for your project

    public class MyRequiredAttribute : RequiredAttribute
    {
        //Your custom code
    }
    
  2. Modify your MyRequiredAttributeAdapter code as shown. Notice that you now need to inherit from the generic DataAnnotationsModelValidator class, which allows you pass in your custom MyRequiredAttribute

    public class MyRequiredAttributeAdapter : DataAnnotationsModelValidator<MyRequiredAttribute>
    {
        public MyRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, MyRequiredAttribute attribute)
            : base(metadata, context, attribute)
        {
            if (string.IsNullOrWhiteSpace(attribute.ErrorMessage)
                && string.IsNullOrWhiteSpace(attribute.ErrorMessageResourceName)
                && attribute.ErrorMessageResourceType == null)
            {
                attribute.ErrorMessageResourceType = typeof(Resources.Validation.Messages);
                attribute.ErrorMessageResourceName = "PropertyValueRequired";
            }
        }
    }
    
  3. Add this to Global.asax (modified from what you have in your partial solution)

    DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyRequiredAttribute), typeof(MyRequiredAttributeAdapter));
    

To override the default data type message for non-null properties such as DateTime and int,
implement an own MyClientDataTypeModelValidatorProvider based on the MVC ClientDataTypeModelValidatorProvider.
Add that instance to ModelValidatorProviders.Providers, and removed the default one.

So, put this into Global.asax:

var clientDataTypeModelValidatorProviderIndex = ModelValidatorProviders.Providers.FindIndex(modelValidatorProvider => modelValidatorProvider is ClientDataTypeModelValidatorProvider);
ModelValidatorProviders.Providers.RemoveAt(clientDataTypeModelValidatorProviderIndex);
ModelValidatorProviders.Providers.Add(new MyClientDataTypeModelValidatorProvider());

Tested with MVC 5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!