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?
Well I'm really late to the party, but for what it is worth, I have blogged about this very subject whereby I create a
EnumHelper
class that enables very easy transformation.http://jnye.co/Posts/4/creating-a-dropdown-list-from-an-enum-in-mvc-and-c%23
In your controller:
In your View:
The helper class:
So without Extension functions if you are looking for simple and easy.. This is what I did
where XXXXX.Sites.YYYY.Models.State is an enum
Probably better to do helper function, but when time is short this will get the job done.
You can also use my custom HtmlHelpers in Griffin.MvcContrib. The following code:
Generates:
https://github.com/jgauffin/griffin.mvccontrib
Expanding on Prise and Rune's answers, if you'd like to have the value attribute of your select list items map to the integer value of the Enumeration type, rather than the string value, use the following code:
Instead of treating each Enumeration value as a TEnum object, we can treat it as a object and then cast it to integer to get the unboxed value.
Note: I also added a generic type constraint to restrict the types for which this extension is available to only structs (Enum's base type), and a run-time type validation which ensures that the struct passed in is indeed an Enum.
Update 10/23/12: Added generic type parameter for underlying type and fixed non-compilation issue affecting .NET 4+.
@Simon Goldstone: Thanks for your solution, it can be perfectly applied in my case. The only problem is I had to translate it to VB. But now it is done and to save other people's time (in case they need it) I put it here:
End You use it like this: