dimanche 10 mai 2015

Passing an enum as an annotation parameter and getting list of itens

I created a custom attribute, that will be used to define that the property is used in a DropDownList. So the code of attribute is this:

public class DropDownList : Attribute
    {

        public Type EnumType { get; set; }

        public DropDownList(Type type)
        {
            this.EnumType = type;

        }

    }

I can't pass the enum as paramater, i only could do this passing the type of enum, like this:

class TestViewModel{

[DropDownList(typeof(MyEnums.EnumTest)]
prop int MyProp {get; set;}

}

I have a HTML extension, that needs to work like this:

public HtmlString AddSelectFor<TValue>(Expression<Func<TModel, TValue>> expression){

       var memberExpression = expression.Body as MemberExpression;
       var attribute = memberExpression.Member.GetCustomAttributes(typeof(MyProj.Attributes.DropDownList), false).FirstOrDefault() as MyProj.Attributes.DropDownList;

       // HERE i need to get the list of enum itens
       var itens = Enum.GetValues(attribute.EnumType);

       return HtmlHelper.DropDownListFor(expression, list);
}

The problem is, i don't have the enum, i have only the type, because it needs to be generic. So i can't do the cast to create the list used on "HtmlHelper.DropDownListFor".

How can i do that? Thanks

Aucun commentaire:

Enregistrer un commentaire