Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set/remove attributes dynamically in c#?

I am using from attribute validation in my project.

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

In some case DepartmentCode isn't required. How can I dynamically ignore Validation in my case?

like image 711
M.Azad Avatar asked Feb 21 '12 15:02

M.Azad


People also ask

How do I add attributes to my property at runtime?

It is not possible to add Attributes in run-time. Attributes are static and cannot be added or removed.

Can we remove property from list in C #?

We can use the RemoveAt method to remove an item at the specified position within a List. The Remove method removes the first occurrence of a specific object from a List. The Remove method takes an item as its parameter. We can use the RemoveAt method to remove an item at the specified position within a List.

What are attributes C#?

In C#, attributes are classes that inherit from the Attribute base class. Any class that inherits from Attribute can be used as a sort of "tag" on other pieces of code. For instance, there is an attribute called ObsoleteAttribute . This is used to signal that code is obsolete and shouldn't be used anymore.


2 Answers

Take a look at: Remove C# attribute of a property dynamically

Anyway I think the proper solution is to inherit an attribute from RequiredAttribute and override the Validate() method (so you can check when that field is required or not). You may check CompareAttribute implementation if you want to keep client side validation working.

like image 152
Adriano Repetti Avatar answered Oct 02 '22 01:10

Adriano Repetti


Instead of dynamically adding and removing validation, you would be better served to create an attribute that better serves this purpose.

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

like image 28
user338146 Avatar answered Oct 01 '22 23:10

user338146