Access to parent class from user attribute

Is it possible to access the parent class from an attribute.

For example, I would like to create a DropDownListAttribute, which can be applied to the property of the viewmodel class in MVC, and then create a drop-down list from the editor template. I follow a similar line like Kazi Manzur Rashid here .

It adds a collection of categories to the viewdata and retrieves them using the key specified in the attribute.

I would like to do something like below

public ExampleDropDownViewModel {

   public IEnumerable<SelectListItem> Categories {get;set;}

   [DropDownList("Categories")]
   public int CategoryID { get;set; }
}

The attribute takes the name of the property containing the collection binding. I cannot figure out how to access the property of the attribute's parent class. Does anyone know how to do this?

thank

+3
2

. - , , , - :

[MyCustomAttribute(typeof(MyClass))]
public class MyClass {
  ///
}

, , . .

+1

, . :

Type type = typeof(ExampleDropDownViewModel));
// Get properties of your data class
PropertyInfo[] propertyInfo = type.GetProperties( );

foreach( PropertyInfo prop in propertyInfo )
{
   // Fetch custom attributes applied to a property        
   object[] attributes = prop.GetCustomAttributes(true);

   foreach (Attribute attribute in attributes) {
      // we are only interested in DropDownList Attributes..
      if (attribute is DropDownListAttribute) {
    DropDownListAttribute dropdownAttrib = (DropDownListAttribute)attribute;
         Console.WriteLine("table set in attribute: " + dropdownAttrib.myTable);
      }
   }
}
+1

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


All Articles