Many metadata validation rules using DataAnnotations with ASP.Net MVC

I use DataAnnotations and MetadataType in ASP.Net MVC to verify the creation of one of my custom objects through a form on our www site. It works very well.

But now we also need to be able to create the same object through the form on our internal admin site.

However, the verification rules are slightly different in that some fields are required on the www site, which are not required when we fill out the form through our internal administration system.

In addition, I would like to provide the same field of different DisplayNames and different verification messages depending on which site / form the data is collected, etc.

How can I essentially have two different types of metadata and indicate which one I want to use when checking on the admin site, compared to the www site. Ie two different sets of validation rules and the ability to specify which one I'm checking for.

I used my MetadataType using the Buddy (partial) classes, since my objects are automatically generated by LINQ to SQL.

+4
source share
2 answers

I used to be in the same situation. At that time, I searched, but found that there was no solution that would give you two sets of validation rules in the same class.

The way I decided was to use presentation models. You have the β€œbasic” model classes, and you want different user interfaces (in this case, the web interface and the admin user interface) to have different validation rules. In this case, you do not need friend classes for model classes, since you do not want to apply validation rules for the model class itself, instead you need to inherit from your model class to create two presentation model classes, one for websites and one for websites admin interface and apply validation rules using DataAnnotations in different ways on these classes according to your needs. You can also β€œenhance” the view model classes with additional attributes specific to the user interface.

I know that this solution is not ideal, because you will have your own verification rules in two different places, and this is usually not recommended, but it works, and it is not so bad, especially if the application is not very large. The only other solution is to manually check which place the user is using from the user (web or admin), and then add model state errors accordingly. But I would not recommend doing it that way.

I would love to hear if anyone has a better solution for this.

+1
source

Source: https://habr.com/ru/post/1334737/


All Articles