Load a Dropdownlist based on an enum - Asp.net core

1

I have an enum PersonNature that relates to the Person table. I need to create a dropdownlist in my view that displays the list of PeopleNature (PHYSICAL AND LEGAL PERSON), including showing the personal nature related to the current record, according to the viewmodel. Does anyone know how to help me?

PeopleNature

 public enum PessoaNatureza
 {
     [Description("FÍSICA")]
     Fisica = 1,
     [Description("JURÍDICA")]
     Juridica = 2
 }

PersonaViewModel

 public class PessoaViewModel
 {
     [Key]
     [DisplayName("Código")]
     public int Id { get; set; }

     [DisplayName("Natureza")]
     [Display(Name = "Natureza")]
     [RegularExpression(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$")]
     [Required(ErrorMessage = "Escolha uma Natureza de Pessoa")]
     public int PessoaNaturezaId { get; set; }
     public List<SelectListItem> PessoasNaturezas { get; set; }
  }

Edit.cshtml

 <div class="form-group">
      <label asp-for="PessoaNaturezaId" class="col-md-2 control-label"></label>
      <div class="col-md-2">
          <input asp-for="PessoaNaturezaId" class="form-control" />
          @Html.DropDownListFor(model => model.PessoaNaturezaId, Model.PessoaNatureza, "--Selecione--", new { @class = "form-control" })
          <span asp-validation-for="PessoaNaturezaId" class="text-danger"></span>
      </div>
  </div>
    
asked by anonymous 27.02.2018 / 15:53

2 answers

2

You can create a static class and manipulate your Enum to popular your SelectListItem

public static class ExtensaoDeEnumerador
{
    public static string GetEnumDescription<T>(string value)
    {
        Type type = typeof(T);
        var name = Enum.GetNames(type).Where(f => f.Equals(value, StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault();

        if (name == null)
        {
            return string.Empty;
        }

        var field = type.GetField(name);
        var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
        return customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name;
    }

    public static IEnumerable<SelectListItem> EnumToSelectList<T>(string tipoCase = null)
    {
        return (Enum.GetValues(typeof(T)).Cast<T>().Select(
            e => new SelectListItem()
            {
                Text = (tipoCase == null ? GetEnumDescription<T>(e.ToString()) : (tipoCase.ToUpper() == "U" ? GetEnumDescription<T>(e.ToString()).ToUpper() : GetEnumDescription<T>(e.ToString()).ToLower())),
                Value = e.ToString()
            })).ToList();
    }
}

View the call.

pessoaViewModel.PessoasNaturezas = ExtensaoDeEnumerador.EnumToSelectList<PessoaNatureza>("U").OrderBy(x => x.Text);
    
27.02.2018 / 17:36
1

There is another option, though I prefer Marconcilio's approach to solving the functionality as a whole and not just this timely issue. But I also do not much agree with the structure presented in the question.

You can add a constructor to your ViewModel where you populate the List<SelectListItem> PessoasNaturezas with Enum values and mark the populated value in PessoaNaturezaId as selected.

public class PessoaViewModel
{
    [Key]
    [DisplayName("Código")]
    public int Id { get; set; }

    [DisplayName("Natureza")]
    [Display(Name = "Natureza")]
    [RegularExpression(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$")]
    [Required(ErrorMessage = "Escolha uma Natureza de Pessoa")]
    public int PessoaNaturezaId { get; set; }
    public List<SelectListItem> PessoasNaturezas { get; set; }

    public PessoaViewModel()
    {
        var listaPessoaNatureza = from PessoaNatureza pn in Enum.GetValues(typeof(PessoaNatureza))
                                  select new SelectListItem
                                  {
                                      Value = ((int)pn).ToString(),
                                      Text = Enum.GetName(typeof(PessoaNatureza), pn),
                                      Selected = PessoaNaturezaId == (int)pn ? true : false
                                  };
        PessoasNaturezas = listaPessoaNatureza.ToList();
    }
}

And in your view you can keep the default helpers using <select asp-for..

<div class="form-group">
    <label asp-for="PessoaNaturezaId" class="col-md-2 control-label"></label>
    <div class="col-md-2">
        <select asp-for="PessoaNaturezaId" asp-items="Model.PessoasNaturezas">
            <option value="">--Selecione--</option>
        </select>
        <span asp-validation-for="PessoaNaturezaId" class="text-danger"></span>
    </div>
</div>

This "solves" your problem, but I recommend you opt for the solution presented by your colleague. I only recommend my proposal if you have difficulties understanding or implementing the other suggestion.

    
27.02.2018 / 18:28