JsonResult Display DisplayName of an Enum

0

I'm having a problem returning the DisplayName of an enum

I have the following Enum

public enum TipoPessoa
    {
        [Description("Pessoa Fisica")]
        [Display(Name = "Pessoa Fisica")]
        [JsonProperty("Pessoa Fisica")]
        Fisica = 0,

        [Display(Name = "Pessoa Juridica")]
        [Description("Pessoa Juridica")]
        [JsonProperty("Pessoa Juridica")]
        Juridica = 1
    }

and the following view model

public class EmpresaViewerViewModel
{
    public int Id { get; set; }

    [Display(Name = "Razão Social")]
    public string RazaoSocial { get; set; }

    [Display(Name = "Nome Fantasia")]
    public string NomeFantasia { get; set; }

    public int CNPJ { get; set; }

    [Display(Name = "Inscrição Estadual")]
    public int InscricaoEstadual { get; set; }

    [Display(Name = "Tipo de Pessoa")]
    public TipoPessoa TipoPessoa { get; set; }

    [Display(Name = "Código do Regime Tributário")]
    public CRT CRT { get; set; }

    public string Logradouro { get; set; }

    public string Complemento { get; set; }

    [DataType(DataType.PostalCode)]
    public string CEP { get; set; }

    public string Numero { get; set; }

    public string Bairro { get; set; }

    public string Cidade { get; set; }

    public string Estado { get; set; }

    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [DataType(DataType.PhoneNumber)]
    public string Telefone { get; set; }

    [DataType(DataType.PhoneNumber)]
    public string TelefoneCelular { get; set; }
}

and the following method in the controller

public JsonResult GetAll(string searchPhrase, int current = 1, int rowCount = 10)
    {
        // Ordenacao
        string columnKey = Request.Form.AllKeys.Where(k => k.StartsWith("sort")).First();
        string order = Request[columnKey];
        string field = columnKey.Replace("sort[", String.Empty).Replace("]", String.Empty);

        string fieldOrdened = String.Format("{0} {1}", field, order);

        List<PessoaEmpresa> pessoaEmpresa = repositoryEmpresa.Select();

        List<PessoaEmpresa> empresaPaginada = pessoaEmpresa.OrderBy(fieldOrdened).Skip((current - 1) * rowCount).Take(rowCount).ToList();

        List<EmpresaViewerViewModel> viewModel = AutoMapperManager.Instance.Mapper.Map<List<PessoaEmpresa>, List<EmpresaViewerViewModel>>(empresaPaginada);

        return  Json(new
        {
            rows = viewModel,
            current = current,
            rowCount = rowCount,
            total = pessoaEmpresa.Count()
        }, JsonRequestBehavior.AllowGet);
    }

But the json returned business type and crt comes as 0 or 1 and not the attribute name

    
asked by anonymous 12.09.2017 / 19:47

2 answers

1

You can create a class to capture the custom attribute of the class property.

Here is an example of a custom class and just below its use

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;

public static class EnumHelper<T>
{
    public static IList<T> GetValues(Enum value)
    {
        var enumValues = new List<T>();

        foreach (FieldInfo fi in value.GetType().GetFields(BindingFlags.Static | BindingFlags.Public))
        {
            enumValues.Add((T)Enum.Parse(value.GetType(), fi.Name, false));
        }
        return enumValues;
    }

    public static T Parse(string value)
    {
        return (T)Enum.Parse(typeof(T), value, true);
    }

    public static IList<string> GetNames(Enum value)
    {
        return value.GetType().GetFields(BindingFlags.Static | BindingFlags.Public).Select(fi => fi.Name).ToList();
    }

    public static IList<string> GetDisplayValues(Enum value)
    {
        return GetNames(value).Select(obj => GetDisplayValue(Parse(obj))).ToList();
    }

    private static string lookupResource(Type resourceManagerProvider, string resourceKey)
    {
        foreach (PropertyInfo staticProperty in resourceManagerProvider.GetProperties(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public))
        {
            if (staticProperty.PropertyType == typeof(System.Resources.ResourceManager))
            {
                System.Resources.ResourceManager resourceManager = (System.Resources.ResourceManager)staticProperty.GetValue(null, null);
                return resourceManager.GetString(resourceKey);
            }
        }

        return resourceKey; // Fallback with the key name
    }

    public static string GetDisplayValue(T value)
    {
        var fieldInfo = value.GetType().GetField(value.ToString());

        var descriptionAttributes = fieldInfo.GetCustomAttributes(
            typeof(DisplayAttribute), false) as DisplayAttribute[];

        if (descriptionAttributes[0].ResourceType != null)
            return lookupResource(descriptionAttributes[0].ResourceType, descriptionAttributes[0].Name);

        if (descriptionAttributes == null) return string.Empty;
        return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].Name : value.ToString();
    }
}

How to call the EnumHelper class in the view:

<ul>
    @foreach (var value in @EnumHelper<UserPromotion>.GetValues(UserPromotion.None))
    {
         if (value == Model.JobSeeker.Promotion)
        {
            var description = EnumHelper<UserPromotion>.GetDisplayValue(value);
            <li>@Html.DisplayFor(e => description )</li>
        }
    }
</ul>

In your View Model, change the Property Type property like this:

    TipoPessoa tipoPessoa;
        string tipoPessoa;
[Display(Name = "Tipo de Pessoa")]
        public string TipoPessoa {
            get {
                tipoPessoa = EnumHelper.<TipoPessoa>.GetDisplayValue(value);
                return tipoPessoa;
            }
            set {
                tipoPessoa = value;
            }
        }

Reference: Enum Helper

    
12.09.2017 / 20:09
1

Try this, considering that you are using the Newtonsoft.Json library:

[JsonConverter(typeof(StringEnumConverter))] // Adicione isto
public enum TipoPessoa
{
   [Description("Pessoa Fisica")]
   [Display(Name = "Pessoa Fisica")]
   [JsonProperty("Pessoa Fisica")]
   [EnumMember(Value = "Pessoa Fisica")] // Adicione isto
   Fisica = 0,

   [Display(Name = "Pessoa Juridica")]
   [Description("Pessoa Juridica")]
   [JsonProperty("Pessoa Juridica")]
   [EnumMember(Value = "Pessoa Juridica")] // Adicione isto
   Juridica = 1
}
    
12.09.2017 / 20:00