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

后端 未结 30 1953
不知归路
不知归路 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条回答
  •  Happy的楠姐
    2020-11-21 17:03

    Another fix to this extension method - the current version didn't select the enum's current value. I fixed the last line:

    public static SelectList ToSelectList(this TEnum enumObj) where TEnum : struct
        {
            if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");
    
            var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                           select new
                           {
                               ID = (int)Enum.Parse(typeof(TEnum), e.ToString()),
                               Name = e.ToString()
                           };
    
    
            return new SelectList(values, "ID", "Name", ((int)Enum.Parse(typeof(TEnum), enumObj.ToString())).ToString());
        }
    

提交回复
热议问题