Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net-mvc

I need to declare a lot of properties of a model that all have the same attributes. I was wondering if there was any 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 those 2 attributes (required and range), The only thing differing is the name of the properties. Is there any way to declare these in a way that involves less repetition?

like image 309
DatBear Avatar asked Mar 14 '13 06:03

DatBear


People also ask

Can we use two multiple models with a single view?

You can use multiple models in a single view by creating a common model for all the models that are to be used in a single view. To achieve this, refer to the following steps. First, create a new model (common for all models) and refer all other models that are to be used in the same view.

Can a controller have multiple views?

Yes You can use multiple View in one Controller.


1 Answers

There is no any built-in feature for your requirement however you can achieve this functionality using ModelValidatorProviders. You have to create your own provider and pass it to MVC. Create your own attribute which will accept type of annotation as well as array of properties to which it should get applied. and then you can write required logic inside that attribute accordingly. Have a look at this link it will surely give you hint how to get this done..

CustomModelValidatorProvider

like image 196
K D Avatar answered Oct 20 '22 15:10

K D