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 this:
public enum ItemTypes
{
Movie = 1,
Game = 2,
Book = 3
}
How do I go about creating a dropdown with these values using the Html.DropDownList
extension method?
Or is my best bet to simply create a for loop and create the Html elements manually?
This is Rune & Prise answers altered to use the Enum
int
value as the ID.Sample Enum:
Extension method:
Sample of usage:
Remember to Import the namespace containing the Extension method
Sample of generated HTML:
Note that the item that you use to call the
ToSelectList
on is the selected item.Building on Simon's answer, a similar approach is to get the Enum values to display from a Resource file, instead of in a description attribute within the Enum itself. This is helpful if your site needs to be rendered in more than one language and if you were to have a specific resource file for Enums, you could go one step further and have just Enum values, in your Enum and reference them from the extension by a convention such as [EnumName]_[EnumValue] - ultimately less typing!
The extension then looks like:
Resources in the Enums.Resx file looking like ItemTypes_Movie : Film
One other thing I like to do is, instead of calling the extension method directly, I'd rather call it with a @Html.EditorFor(x => x.MyProperty), or ideally just have the whole form, in one neat @Html.EditorForModel(). To do this I change the string template to look like this
If this interests you, I've put a much more detailed answer here on my blog:
http://paulthecyclist.com/2013/05/24/enum-dropdown/
To solve the problem of getting the number instead of text using Prise's extension method.
I ended up creating extention methods to do what is essentially the accept answer here. The last half of the Gist deals with Enum specifically.
https://gist.github.com/3813767
Here is a better encapsulated solution:
https://www.spicelogic.com/Blog/enum-dropdownlistfor-asp-net-mvc-5
Say here is your model:
Sample Usage:
Generated UI:
And generated HTML
The Helper Extension Source Code snap shot:
You can download the sample project from the link I provided.
EDIT: Here's the code: