Saltar al contenido

¿Cómo se crea una lista desplegable a partir de una enumeración en ASP.NET MVC?

Deseamos compartirte la mejor información que hallamos on line. Esperamos que te sea útil y si deseas comentarnos algo que nos pueda ayudar a crecer puedes hacerlo..

Solución:

Para MVC v5.1 use Html.EnumDropDownListFor

@Html.EnumDropDownListFor(
    x => x.YourEnumField,
    "Select My Type", 
    new  @class = "form-control" )

Para MVC v5 use EnumHelper

@Html.DropDownList("MyType", 
   EnumHelper.GetSelectList(typeof(MyType)) , 
   "Select My Type", 
   new  @class = "form-control" )

Para MVC 5 e inferior

Enrollé la respuesta de Rune en un método de extensión:

namespace MyApp.Common

    public static class MyExtensions
        public static SelectList ToSelectList(this TEnum enumObj)
            where TEnum : struct, IComparable, IFormattable, IConvertible
        
            var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                select new  Id = e, Name = e.ToString() ;
            return new SelectList(values, "Id", "Name", enumObj);
        
    

Esto le permite escribir:

ViewData["taskStatus"] = task.Status.ToSelectList();

por using MyApp.Common

Sé que llegué tarde a la fiesta en esto, pero pensé que podría encontrar útil esta variante, ya que también le permite usar cadenas descriptivas en lugar de constantes de enumeración en el menú desplegable. Para hacer esto, decore cada entrada de enumeración con un [System.ComponentModel.Description] attribute.

Por ejemplo:

public enum TestEnum

  [Description("Full test")]
  FullTest,

  [Description("Incomplete or partial test")]
  PartialTest,

  [Description("No test performed")]
  None

Aquí está mi código:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Reflection;
using System.ComponentModel;
using System.Linq.Expressions;

 ...

 private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
    
        Type realModelType = modelMetadata.ModelType;

        Type underlyingType = Nullable.GetUnderlyingType(realModelType);
        if (underlyingType != null)
        
            realModelType = underlyingType;
        
        return realModelType;
    

    private static readonly SelectListItem[] SingleEmptyItem = new[]  new SelectListItem  Text = "", Value = ""  ;

    public static string GetEnumDescription(TEnum value)
    
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if ((attributes != null) && (attributes.Length > 0))
            return attributes[0].Description;
        else
            return value.ToString();
    

    public static MvcHtmlString EnumDropDownListFor(this HtmlHelper htmlHelper, Expression> expression)
    
        return EnumDropDownListFor(htmlHelper, expression, null);
    

    public static MvcHtmlString EnumDropDownListFor(this HtmlHelper htmlHelper, Expression> expression, object htmlAttributes)
    
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        Type enumType = GetNonNullableModelType(metadata);
        IEnumerable values = Enum.GetValues(enumType).Cast();

        IEnumerable items = from value in values
            select new SelectListItem
            
                Text = GetEnumDescription(value),
                Value = value.ToString(),
                Selected = value.Equals(metadata.Model)
            ;

        // If the enum is nullable, add an 'empty' item to the collection
        if (metadata.IsNullableValueType)
            items = SingleEmptyItem.Concat(items);

        return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
    

A continuación, puede hacer esto en su vista:

@Html.EnumDropDownListFor(model => model.MyEnumProperty)

¡Espero que esto te ayude!

**EDITAR 2014-JAN-23: Microsoft acaba de lanzar MVC 5.1, que ahora tiene una función EnumDropDownListFor. Lamentablemente, no parece respetar la [Description] attribute por lo que el código anterior sigue en pie. Consulte la sección Enum en las notas de la versión de Microsoft para MVC 5.1.

Actualización: es compatible con la pantalla attribute [Display(Name = "Sample")] sin embargo, entonces uno puede usar eso.

[Update – just noticed this, and the code looks like an extended version of the code here: https://blogs.msdn.microsoft.com/stuartleeks/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums/, with a couple of additions. If so, attribution would seem fair ;-)]

En ASP.NET MVC 5.1agregaron el EnumDropDownListFor() ayudante, por lo que no hay necesidad de extensiones personalizadas:

Modelo:

public enum MyEnum

    [Display(Name = "First Value - desc..")]
    FirstValue,
    [Display(Name = "Second Value - desc...")]
    SecondValue

Vista:

@Html.EnumDropDownListFor(model => model.MyEnum)

Uso de Tag Helper (ASP.NET MVC 6):