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
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.
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With