1

I am trying to make a custom data annotation attribute with a simple bool result, if the property have the data annotation, then perform an action. My objective is to make an array with all the properties that have the Filter dataanotation to later make a DropDownListFor in view with that information.

public class Foo
{
    public string property1 { get; set; }

    [Filter]
    public string property2 { get; set; }
}

Then somewhere in the code:

        IList<PropertyInfo> properties = typeof(Foo).GetProperties().ToList();
        ArrayList propertiesThatCanBeFiltered = new ArrayList();
        foreach (var propertyInfo in properties)
        {
            if (propertyInfo.Attributes("Filter").Exists)
            {
                propertiesThatCanBeFiltered.Add(propertyInfo.Name);
            }

        }
Gonzalo
  • 11
  • 4
  • This is where Actionfilters comes in play. http://msdn.microsoft.com/en-us/library/dd410056(v=vs.100).aspx – Ahmed ilyas Jan 14 '15 at 15:25
  • can you try something like ((DisplayAttribute)(myFooObject.GetType().GetProperty("property2 ").GetCustomAttributes(typeof(DisplayAttribute),true)[0])); – Anshul Nigam Jan 14 '15 at 15:54

2 Answers2

0

You need GetCustomAttribute<T> Documentation

And here how to apply it:

IList<PropertyInfo> properties = typeof(Foo).GetProperties().ToList();
ArrayList propertiesThatCanBeFiltered = new ArrayList();
foreach (var propertyInfo in properties)
{
    var filterAttribute = propertyInfo.GetCustomAttribute<Filter>();
    if (filterAttribute != null)
    {
        propertiesThatCanBeFiltered.Add(propertyInfo.Name);
    }

}
trailmax
  • 34,305
  • 22
  • 140
  • 234
-1

I believe custom ActionFilters is what you are after:

http://msdn.microsoft.com/en-us/library/dd410056(v=vs.100).aspx

This is what you are stating in your question where when a certain attribute is applied to then execute some logic... AF's does just that.

Other than that, there is a way to create your own custom data annotation:

How to create Custom Data Annotation Validators

http://weblogs.asp.net/brijmohan/asp-net-mvc-3-custom-validation-using-data-annotations

but it depends exactly what you want to do. Do not get the 2 mixed up together.

Community
  • 1
  • 1
Ahmed ilyas
  • 5,722
  • 8
  • 44
  • 72
  • The thing is, I don't need to check or filter an ActionResult or Action at all, I need to make a DropDownList with only the properties of an model object with the "Filter" present. – Gonzalo Jan 14 '15 at 15:32
  • you need to elaborate further on what you exactly want. what makes you think an attribute will do what you want for this context? :) – Ahmed ilyas Jan 14 '15 at 15:42
  • Ok, I explained myself a bit better =) – Gonzalo Jan 14 '15 at 16:00