How do you create a dropdownlist from an enum in ASP.NET MVC?

后端 未结 30 2324
不知归路
不知归路 2020-11-21 16:36

I\'m trying to use the Html.DropDownList extension method but can\'t figure out how to use it with an enumeration.

Let\'s say I have an enumeration like

30条回答
  •  耶瑟儿~
    2020-11-21 16:54

    Expanding on Prise and Rune's answers, if you'd like to have the value attribute of your select list items map to the integer value of the Enumeration type, rather than the string value, use the following code:

    public static SelectList ToSelectList(T enumObj) 
        where T : struct
        where TU : struct
    {
        if(!typeof(T).IsEnum) throw new ArgumentException("Enum is required.", "enumObj");
    
        var values = from T e in Enum.GetValues(typeof(T))
                     select new { 
                        Value = (TU)Convert.ChangeType(e, typeof(TU)),
                        Text = e.ToString() 
                     };
    
        return new SelectList(values, "Value", "Text", enumObj);
    }
    

    Instead of treating each Enumeration value as a TEnum object, we can treat it as a object and then cast it to integer to get the unboxed value.

    Note: I also added a generic type constraint to restrict the types for which this extension is available to only structs (Enum's base type), and a run-time type validation which ensures that the struct passed in is indeed an Enum.

    Update 10/23/12: Added generic type parameter for underlying type and fixed non-compilation issue affecting .NET 4+.

提交回复
热议问题