MVC - there is a way to declare several properties in a model with the same attributes, different names

I need to declare many model properties that have the same attributes. I was wondering if there is a way to do this in MVC.

[Required] [Range(0, 4, ErrorMessage = "Integrity is required.")] public int Integrity { get; set; } [Required] [Range(0, 4, ErrorMessage = "Empathy is required.")] public int Empathy { get; set; } 

I have a bunch of fields that use these 2 attributes (a range is also required). The only difference is the name of the properties. Is there a way to declare them so that they do not repeat?

+7
source share
1 answer

There is no built-in function for your requirement, however you can achieve this functionality with ModelValidatorProviders. You must create your own provider and pass it MVC. Create your own attribute that will accept the type of annotation, as well as an array of properties to which it should apply. and then you can write the necessary logic inside this attribute. Look at this link, it will surely give you a hint on how to do this.

CustomModelValidatorProvider

+1
source

All Articles