This question already has an answer here:
I've been finding all over the place that the common way to bind Enums to DropDowns is through helper methods, which seems a bit overbearing for such a seemingly simple task.
What is the best way to bind Enums to DropDownLists in ASP.Net MVC 4?
In my Controller:
In my View:
Enums are supported by the framework since MVC 5.1:
Displayed text can be customized:
MSDN link: http://www.asp.net/mvc/overview/releases/mvc51-release-notes#Enum
You can to this:
The solution from PaulTheCyclist is spot on. But I wouldn't use RESX (I'd have to add a new .resx file for each new enum??)
Here is my HtmlHelper Expression:
Here is how I declare my enums:
And here is the call from a Razor View:
Where
@Model.LoanType
is an model property of the LoanApplicationType typeUPDATE: Sorry, forgot to include code for the helper function ToDescription()
Extending the html helper to do it works well, but if you'd like to be able to change the text of the drop down values based on DisplayAttribute mappings, then you would need to modify it similar to this,
(Do this pre MVC 5.1, it's included in 5.1+)
Technically, you don't need a helper method, since
Html.DropdownListFor
only requires aSelectList
orIenumerable<SelectListItem>
. You can just turn your enums into such an output and feed it in that way.I use a static library method to convert enums into
List<SelectListItem>
with a few params/options:Your ViewModel can pass in the options you want. Here's a fairly complex one:
So you wire your View's
DropDownList
against thatIEnumerable<SelectListItem>
property.