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

后端 未结 30 1946
不知归路
不知归路 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 17:08

    A super easy way to get this done - without all the extension stuff that seems overkill is this:

    Your enum:

        public enum SelectedLevel
        {
           Level1,
           Level2,
           Level3,
           Level4
        }
    

    Inside of your controller bind the Enum to a List:

        List myLevels = Enum.GetValues(typeof(SelectedLevel)).Cast().ToList();
    

    After that throw it into a ViewBag:

        ViewBag.RequiredLevel = new SelectList(myLevels);
    

    Finally simply bind it to the View:

        @Html.DropDownList("selectedLevel", (SelectList)ViewBag.RequiredLevel, new { @class = "form-control" })
    

    This is by far the easiest way I found and does not require any extensions or anything that crazy.

    UPDATE: See Andrews comment below.

提交回复
热议问题