How to set / remove attributes dynamically in C #?

I use attribute verification in my project.

[Required(ErrorMessage = "DepartmentCode is Required")] public string DepartmentCode { get; set; } 

In some cases, DepartmentCode is not required. How can I dynamically ignore validation in my case?

+6
source share
4 answers

Look at: dynamically remove C # attribute of a property

In any case, I believe that the correct solution is to inherit the attribute from RequiredAttribute and override the Validate() method (so you can check if this field is required or not). You can check the implementation of CompareAttribute if you want to keep the check on the client side.

+1
source

Instead of dynamically adding and removing validation, you would be better off creating an attribute that is better suited for this purpose.

The following article shows this (MVC3 with client-side validation): http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3. aspx

+1
source

I would remove RequiredAttribute from your model and test it as soon as you click on your controller and test it against any reasons why you won't need it.

If it falls into the case when it is required, and the value does not fill out, add the error to ModelState manually

ModelState.AddModelError("DepartmantCode", "DepartmantCode is Required");

You would simply lose client-side validation.

0
source

I circumvented this problem in the model, in some cases it is not perfect, but it is the cheapest and fastest way.

 public string NonMandatoryDepartmentCode { get { return DepartmentCode; } set { DepartmentCode = value; } } 

I used this approach for MVC when the base model I inherited contains attributes that I would like to override.

0
source

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


All Articles