How to Dropdown ASP NET MVC

Asked

Viewed 1,183 times

6

I have a DTO class

[Serializable]
    public class PerfilDTO
    {
        public int Codigo { get; set; }
        public string Descricao { get; set; }
        public SituacaoEnum Situacao { get; set; }
        public List<PerfilFuncionalidadeDTO> PerfilFuncionalidade { get; set; }

    }

And in that DTO I have mine SituacaoEnum which is the below:

 public enum SituacaoEnum
    {
        [Description("Ativo")]
        Ativo = 1,
        [Description("Inativo")]
        Inativo = 2
    }

In my view I have the following:

@model IEnumerable<ControleAcesso.PerfilDTO>

any html and:

 @Html.DropDownListFor(this.Model.First().Situacao)

How to dropdown from what I have?

3 answers

4

@{  var lstOpcoes = Enum.GetValues(typeof(SituacaoEnum)).OfType<SituacaoEnum>().Select(sa => 
    new SelectListItem 
        {
            Text = sa.ToString(), 
            Value = ((int)sa).ToString()
        }).ToList();
}
@Html.DropDownListFor(dtos => dtos.First().Situacao, lstOpcoes)
  • which necessarily dtos => dtos.First().Situacao do? I put in mine by asking in the parameter but did not understand the pq rs

  • It indicates which parameter will be filled in. In this case, the field Situacao of the first record of dtos. I don’t think that’s the right approach, but it doesn’t get in the way of the answer.

  • 1

    It’s... something tells me I’m going to get a 5 minute stop clock spanking from Asp-net mvc yet. rs. In fact it works perfectly. Thank you!

2

Hello, @okevinlira

Complementing the reply to @Cigano, you will notice that often you will need to repeat that snippet of code in which you create a list of SelectListItem, so that the options in the dropdownlist are created with the values contained in the Enum.

I suggest you make a Extension method for this as I show below:

public static class DropDownListHelper
{
    public static List<SelectListItem> DropDownListEnum<T>(this HtmlHelper helper)
    {
        List<SelectListItem> listaItens = new List<SelectListItem>();
        SelectListItem itemVazio = new SelectListItem();
        itemVazio.Text = "Selecione uma opção";
        itemVazio.Value = "";
        listaItens.Add(itemVazio);

        SelectListItem itemLista;

        foreach (Enum item in Enum.GetValues(typeof(T)))
        {
            itemLista = new SelectListItem();

            itemLista.Value = item.ToString();
            itemLista.Text = item.Descricao();

            listaItens.Add(itemLista);
        }

        return listaItens;
    }
}

After that your DropDownListFor shall be assembled as follows::

@Html.DropDownListFor(dtos => dtos.First().Situacao, Html.DropDownListEnum<SituacaoEnum>())

In addition to allowing you to use with any other enum!

Found simpler?

  • I liked it. Very generic. + 1.

  • I found yes! I will edit my reply and show how I did it with just another extension. See if Like also @Ciganomorrisonmendez

  • I used Reflection to take the Attribute that is on top of the Enum and create the text :)

2


public static class DropDownListHelper
    {
        public static List<SelectListItem> DropDownListEnum<T>(this HtmlHelper helper)
        {
            List<SelectListItem> listaItens = new List<SelectListItem>();
            SelectListItem itemVazio = new SelectListItem();
            itemVazio.Text = "Selecione uma opção";
            itemVazio.Value = "";
            listaItens.Add(itemVazio);

            SelectListItem itemLista;
            //int value = 1;
            //string description = Enumerations.GetEnumDescription((MyEnum)value);
            foreach (Enum item in Enum.GetValues(typeof(T)))
            {
                itemLista = new SelectListItem { Value = item.ToString(), Text = GetDescription(item) };
                listaItens.Add(itemLista);
            }

            return listaItens;
        }

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

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

            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                return attrs != null && attrs.Length > 0 ? ((DescriptionAttribute) attrs[0]).Description : en.ToString();
            }

            return en.ToString();
        }
    }

:::EDIT:::

I found a better solution!

  • Using annotated attributes, right? Very well too. + 1.

  • @Ciganomorrisonmendez Let me change the correct answer? to this one? Although all that posted were absurdly good! (except for my first rs)

  • Make yourself at home.

  • 1

    OK, I will leave as it is for now... Thank you very much!! that class became of oak! would not have succeeded without the help of you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.