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

后端 未结 30 1913
不知归路
不知归路 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:57

    I bumped into the same problem, found this question, and thought that the solution provided by Ash wasn't what I was looking for; Having to create the HTML myself means less flexibility compared to the built-in Html.DropDownList() function.

    Turns out C#3 etc. makes this pretty easy. I have an enum called TaskStatus:

    var statuses = from TaskStatus s in Enum.GetValues(typeof(TaskStatus))
                   select new { ID = s, Name = s.ToString() };
    ViewData["taskStatus"] = new SelectList(statuses, "ID", "Name", task.Status);
    

    This creates a good ol' SelectList that can be used like you're used to in the view:

    Status:<%=Html.DropDownList("taskStatus")%>
    

    The anonymous type and LINQ makes this so much more elegant IMHO. No offence intended, Ash. :)

提交回复
热议问题