Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can find Data Annotation attributes and their parameters using reflection

I have some data annotation attribute like this:

[StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")]

How I can Find Data Annotation attributes and their parameters using reflection?

thanks

like image 514
Arian Avatar asked Oct 23 '11 06:10

Arian


People also ask

Which method is used to retrieve the values of the attributes?

First, declare an instance of the attribute you want to retrieve. Then, use the Attribute. GetCustomAttribute method to initialize the new attribute to the value of the attribute you want to retrieve. Once the new attribute is initialized, you can use its properties to get the values.

What is an attribute in data annotation?

We'll use the following Data Annotation attributes: Required – Indicates that the property is a required field. DisplayName – Defines the text to use on form fields and validation messages. StringLength – Defines a maximum length for a string field. Range – Gives a maximum and minimum value for a numeric field.

How to determine attribute in c#?

By using reflection, you can retrieve the information that was defined with custom attributes. The key method is GetCustomAttributes , which returns an array of objects that are the run-time equivalents of the source code attributes.

Which is the namespace for data annotation attributes?

ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.


1 Answers

I assume you have something like this:

[StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")]
public string FirstName {get;set;}

To get the attribute and a property from it:

StringLengthAttribute strLenAttr = 
  typeof(Person).GetProperty("FirstName").GetCustomAttributes(
  typeof(StringLengthAttribute), false).Cast<StringLengthAttribute>().Single();


int maxLen = strLenAttribute.MaximumLength;
like image 177
Anders Abel Avatar answered Sep 20 '22 09:09

Anders Abel