Choose which items from an enumerator appear in an EnumDropDownListFor

2

Is there a way to select only a few items from the enumerator to send to a EnumDropDownListFor ?

For example:

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

And I would like that in a given View , in EnumDropDownListFor only the first 2 be reported, another View , the last 2, another 2 the middle, ie that I can choose from some which items will appear in EnumDropDownList

    
asked by anonymous 29.10.2015 / 17:01

1 answer

4

In this case, I do not think it's productive to use EnumDropDownListFor . I think it's best to use DropDownListFor and define all 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 file (in the example below, Linguagem.resx ) and an extension method, below:

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