Choose which items of a enumerator appear in an Enumdropdownlistfor

Asked

Viewed 203 times

2

There is how to select only a few items from the enumerator to send to a EnumDropDownListFor ?

Ex:

public enum Documento
{
   CPF = 1,
   RG = 2,
   CNPJ= 3
   NASCIMENTO = 4
}

And I would like that in a certain View, in the EnumDropDownListFor only the first two, in another View, the last 2, in another the middle 2, ie that I can choose in some way which items will appear in the EnumDropDownList

1 answer

4


For this case I do not find it productive to use EnumDropDownListFor. I think I’d better use the DropDownListFor and define all the logic within:

@Html.DropDownListFor(model => model.Documento, 
    Enum.GetValues(typeof(Documento)).OfType<Documento>()
        .Where(/* Coloque a condição de filtro aqui */)
        .Select(option => new SelectListItem
        {
            Text = option.Literal(),
            Value = option.ToString(),
            Selected = (Model != null) && (Model.Documento == option)
        }), "Selecione...", new { @class = "form-control" })

To display the texts correctly with accents, I use a Resource (in the example below, Linguagem.resx) and an extension method, to be followed:

public static class EnumsExtensions
{
    public static String Literal(this Enum e)
    {
        return Linguagem.ResourceManager.GetString(e.ToString());
    }
}

Browser other questions tagged

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