I need to do a Helper where I pass an Enum and it mounts a DropDownList based on all Enum values, I tried to do it as follows:
C #:
public static HtmlString DropDownListEnumFor(this HtmlHelper htmlHelper, Type _enum, string name, int value)
{
List<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem()
{
Text = string.Empty,
Value = string.Empty
});
//percorre objetos do enum
foreach (var item in (_enum).GetFields())
{
if (item.FieldType == (_enum))
{
//busca atributos definidos
var e = item.GetValue(item);
var nome = AttributesHelper.DescricaoEnum(e);
//carrega list de retorno
if (!string.IsNullOrEmpty(nome))
{
lst.Add(new SelectListItem()
{
Text = nome,
Value = ((int)item.GetValue(item)).ToString(),
Selected = value == e.GetHashCode()
});
}
}
}
MvcHtmlString html = htmlHelper.DropDownList(name, lst, new object { });
return html;
}
public static T Convert<T>(object value)
{
var output = value.ToString();
var member = value.GetType().GetMember(output).First();
var attributes = member.GetCustomAttributes(typeof(T), false);
T obj = attributes.Cast<T>().FirstOrDefault();
return obj;
}
public static string DescricaoEnum(object obj)
{
return Convert<DescriptionAttribute>(obj).Description;
}
Html:
@Html.DropDownListEnumFor(typeof(TipoObjetoEnum), "ddlTeste", 1)
What would be the best way for me to pass an Enum type to my class and be able to do what was mentioned?