Default resource for data annotations in ASP.NET MVC

后端 未结 3 567
一生所求
一生所求 2020-12-24 13:40

There\'s a way to set the default resource to the data annotations validations?

I don\'t wanna make something like this:

[Required(ErrorMessage=\"Nam         


        
3条回答
  •  攒了一身酷
    2020-12-24 14:36

    You could try doing this:

    Add this class somewhere in your project:

     public class ExternalResourceDataAnnotationsValidator : DataAnnotationsModelValidator
    {
        /// 
        /// The type of the resource which holds the error messqages
        /// 
        public static Type ResourceType { get; set; }
    
        /// 
        /// Function to get the ErrorMessageResourceName from the Attribute
        /// 
        public static Func ResourceNameFunc 
        {
            get { return _resourceNameFunc; }
            set { _resourceNameFunc = value; }
        }
        private static Func _resourceNameFunc = attr => attr.GetType().Name;
    
        public ExternalResourceDataAnnotationsValidator(ModelMetadata metadata, ControllerContext context, ValidationAttribute attribute)
            : base(metadata, context, attribute)
        {
            if (Attribute.ErrorMessageResourceType == null)
            {
                this.Attribute.ErrorMessageResourceType = ResourceType;
            }
    
            if (Attribute.ErrorMessageResourceName == null)
            {
                this.Attribute.ErrorMessageResourceName = ResourceNameFunc(this.Attribute);
            }
        }
    }
    

    and in your global.asax, add the following:

    // Add once
    ExternalResourceDataAnnotationsValidator.ResourceType = typeof(CustomDataAnnotationsResources);
    
    // Add one line for every attribute you want their ErrorMessageResourceType replaced.
    DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RangeAttribute), typeof(ExternalResourceDataAnnotationsValidator));
    

    It will look for a property with the same name as the validator type for the error message. You can change that via the ResourceNameFunc property.

    EDIT: AFAIK this works from MVC2 onwards, as DataAnnotationsModelValidatorProvider was introduced in MVC2.

提交回复
热议问题