aleczandru
aleczandru

Reputation: 5459

Getting the parameters and values of an attribute

Hi I am using reflection to iterate over the attributes of the properties of this model:

[Required(ErrorMessage = "Username is required")]
[MaxLength(50, ErrorMessage = "Username should not have more then 50 chars")]
[MinLength(25 , ErrorMessage = "Username should have at least 25 chars")]
 public string UserName { get; set; }

 [Required(ErrorMessage = "Password is required")]
 [StringLength(25)]
 public string Password { get; set; }

 public bool RememberMe { get; set; }

foreach (var propertyInfo in type)
       var attr = propertyInfo.CustomAttributes;
       foreach (var customAttributeData in attr)
       {
             var name = customAttributeData.AttributeType.Name;
       }
}

I managed to get as far as getting the attribute name but I am having trouble in getting the key/value pairs of the attribute constructoro arguments.

How can I have access for example to the constructor arguments of of the attributes and there values?

An example would be being able to get : from the Required attribute ErrorMessage.Name and ErrorMessage.Value

Upvotes: 2

Views: 1862

Answers (3)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 62002

Try to look for one type of attributes at a time:

foreach (var reqAttr in (RequiredAttribute[])propertyInfo.GetCustomAttributes(typeof(RequiredAttribute), false))
{
    // use reqAttr.ErrorMessage and so on, in here
}

Upvotes: 0

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32521

You can use MemberInfo.Name and TypedValue.Value. Here is the code:

foreach (var propertyInfo in typeof(YOUR CLASS).GetProperties())
{
    var attr = propertyInfo.GetCustomAttributesData();

    foreach (var customAttributeData in attr)
    {
        foreach (var item in customAttributeData.NamedArguments)
        {
            var name = item.MemberInfo.Name;
            var value = item.TypedValue.Value;
        }
    }
}

Upvotes: 2

jason
jason

Reputation: 241769

You'll need to use reflection further, using Type.GetProperties on each attribute, and then using PropertyInfo.GetValue to yank out the property values that each attribute publicly exposes.

Upvotes: 1

Related Questions