4

Como eu pego a description usando o html helper EnumDropDownListFor do Asp.net MVC 5 ?

Tenho meu enumerador

public num Dias {
      [Description("Segunda dia de trabalho")]
      Segunda = 1,
      [Description("Terçadia de trabalho")]
      Terca = 2
}

Quando eu uso o html helper do asp.net mvc5

 @Html.EnumDropDownListFor(x => x.Dias);

Ele me retorna os valores : "Segunda,Terca", eu gostaria que retornacem os valores da Description no meu select

3
  • Não entendi!? pode dar um exemplo?
    – Maria
    28/08/2014 às 14:27
  • Atualizei Maria, acho que ficou melhor agora
    – Rod
    28/08/2014 às 14:34
  • Agora ficou @Rod
    – Maria
    28/08/2014 às 14:38

3 Respostas 3

8

Uma alternativa que encontrei é usar a annotation

[Display(Name = "Valor")]

Nela o próprio Html Helper reconhece os valores, não tendo que fazer nada mais que isso

3
  • 1
    Excelente solução... :) 21/09/2014 às 18:23
  • Essa resposta deveria ter sido marcada como solução.
    – user8545
    6/06/2017 às 13:12
  • Obrigado por compartilhar, excelente solução, simples e prática. 19/11/2018 às 14:51
3

Reescrevi, o método static extensivo.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
namespace System.Web.Mvc
{
    public static class MethodsExtensivos
    {
        public static System.Web.Mvc.MvcHtmlString EnumDropDownListDescriptionFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string label = null, object htmlAttributes = null)            
        {
            TModel model = htmlHelper.ViewData.Model;
            TProperty property = default(TProperty);
            if (model != null)
            {
                Func<TModel, TProperty> func = expression.Compile();
                property = func(model);
            }
            TagBuilder select = new TagBuilder("select");            
            if (htmlAttributes != null)
            {
                System.Reflection.PropertyInfo[] properties = htmlAttributes.GetType().GetProperties();
                foreach (System.Reflection.PropertyInfo prop in properties)
                {
                    select.MergeAttribute(prop.Name, (String)prop.GetValue(htmlAttributes, null));
                }
            }            
            Type type = typeof(TProperty);            
            String[] Names = type.GetEnumNames();
            if (label != null)
            {
                TagBuilder option = new TagBuilder("option");
                option.MergeAttribute("value", "0");
                option.InnerHtml = label;
                select.InnerHtml += option.ToString();
            }            
            foreach(string Name in Names) {
                System.Reflection.MemberInfo info = type.GetMember(Name).FirstOrDefault();
                TagBuilder option = new TagBuilder("option");
                if (property != null && property.ToString().Equals(Name))
                {
                    option.MergeAttribute("selected", "selected");
                }
                option.MergeAttribute("value", ((int)Enum.Parse(typeof(TProperty), Name)).ToString());
                var texto = info.CustomAttributes
                        .Select(x => x.ConstructorArguments.Select(a => a.Value))
                        .FirstOrDefault();
                if (texto != null)
                {
                    option.SetInnerText(texto.FirstOrDefault().ToString());
                }
                else
                {
                    option.SetInnerText(Name);
                }
                select.InnerHtml += option.ToString();
            }
            if (!select.Attributes.Where(x => x.Key.ToLower().Equals("id")).Any())
            {
                select.MergeAttribute("id", type.Name);

            }
            if (!select.Attributes.Where(x => x.Key.ToLower().Equals("name")).Any())
            {
                select.MergeAttribute("name", type.Name);
            }
            return MvcHtmlString.Create(select.ToString());
        }            
    }
}

Programando esse código:

@Html.EnumDropDownListDescriptionFor(a => a.Dias)
@Html.EnumDropDownListDescriptionFor(a => a.Dias, "Escolha do Dia da Semana")
@Html.EnumDropDownListDescriptionFor(a => a.Dias, "Escolha do Dia da Semana", new { id="select1", name="select1", css="style1" })

Resultado:

inserir a descrição da imagem aqui

<select id="Dias" name="Dias">
  <option value="10">Segunda dia de trabalho</option>
  <option selected="selected" value="20">Ter&#231;a dia de trabalho</option>
</select>
<select id="Dias" name="Dias">
  <option value="0">Escolha do Dia da Semana</option>
  <option value="10">Segunda dia de trabalho</option>
  <option selected="selected" value="20">Ter&#231;a dia de trabalho</option>
</select>
<select css="style1" id="select1" name="select1">
  <option value="0">Escolha do Dia da Semana</option>
  <option value="10">Segunda dia de trabalho</option>
  <option selected="selected" value="20">Ter&#231;a dia de trabalho</option>
</select>
1
  • Boa solução. Sugiro remover o trecho que atribui valor ao label, pois normalmente os enums são zero-index, e um value="0" seria a primeira opção. Remover essa linha: option.MergeAttribute("value", "0"); 5/03/2017 às 17:17
1

Eu utilizo esse extension method:

public static string GetEnumDescription(this Enum value)
{
    FieldInfo fi = value.GetType().GetField(value.ToString());

    DescriptionAttribute[] attributes =
        (DescriptionAttribute[])fi.GetCustomAttributes(
        typeof(DescriptionAttribute),
        false);

    if (attributes != null &&
        attributes.Length > 0)
        return attributes[0].Description;
    else
        return value.ToString();
}

Que permite recuperar os valores pra depois popular o dropdown dessa forma:

var listaParaDropDown = from EMeuEnum in Enum.GetValues(typeof(EMeuEnum ))
                        select new { Id = e, Nome = e.GetEnumDescription() };

Preencha o dropdown a partir dessa lista.

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .