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?
Html.DropDownListFor only requires an IEnumerable, so an alternative to Prise's solution is as follows. This will allow you to simply write:
[Where SelectedItemType is a field on your model of type ItemTypes, and your model is non-null]
Also, you don't really need to genericize the extension method as you can use enumValue.GetType() rather than typeof(T).
EDIT: Integrated Simon's solution here as well, and included ToDescription extension method.
I found an answer here. However, some of my enums have
[Description(...)]
attribute, so I've modified the code to provide support for that:Hope that helps.
If you want to add localization support just change the s.toString() method to something like this:
In here the typeof(Resources) is the resource you want to load, and then you get the localized String, also useful if your enumerator has values with multiple words.
In .NET Core you can just use this:
Here a Martin Faartoft variation where you can put custom labels which is nice for localization.
Use in view: