Display Name with Razor

1

Do I have this case in my project?

public enum TipoValorCalculoComissao
{
    [Display(Name = "Percentual")]
    Percentual = 1,
    [Display(Name = "Valor")]
    Valor = 2
}

And I would like to put these values in a combo, but I applied the Name instead of the enum description. But the only way I could do this was to create a class this way:

public class TipoValorCalculoComissaoView
{
    public int Valor { get; set; }

    public string Nome { get; set; }
}

And call it this way:

private void ObterTipoValorCalculoComissao()
    {
        ViewBag.TipoValorCalculoComissao = Enum.GetValues(typeof(TipoValorCalculoComissao)).Cast<TipoValorCalculoComissao>()
                                                               .Select(v => new TipoValorCalculoComissaoView
                                                               {
                                                                   Nome = v.ToString(),
                                                                   Valor = (int)v
                                                               }).ToList();
    }

But that way I do not get the Name of the object, someone knows some way to get the Name of the object to display via the razor.

    
asked by anonymous 03.06.2017 / 14:47

1 answer

1

Try something like this:

public static string GetDescription(this System.Enum en)
{
    Type type = en.GetType();

    MemberInfo[] memberInfo = type.GetMember(en.ToString());

    if (memberInfo != null && memberInfo.Length > 0)
    {
        var attrs = memberInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);

        if (attrs != null && attrs.Length > 0)
        {
            return ((DisplayAttribute)attrs[0]).Name;
        }
    }

    return en.ToString();
}
    
03.06.2017 / 15:02