snippetcsharpCritical
How do you create a dropdownlist from an enum in ASP.NET MVC?
Viewed 0 times
netenumaspyouhowfrommvcdropdownlistcreate
Problem
I'm trying to use the
Let's say I have an enumeration like this:
How do I go about creating a dropdown with these values using the
Or is my best bet to simply create a for loop and create the Html elements manually?
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?
Solution
For MVC v5.1 use Html.EnumDropDownListFor
For MVC v5 use EnumHelper
For MVC 5 and lower
I rolled Rune's answer into an extension method:
This allows you to write:
by
@Html.EnumDropDownListFor(
x => x.YourEnumField,
"Select My Type",
new { @class = "form-control" })For MVC v5 use EnumHelper
@Html.DropDownList("MyType",
EnumHelper.GetSelectList(typeof(MyType)) ,
"Select My Type",
new { @class = "form-control" })For MVC 5 and lower
I rolled Rune's answer into an extension method:
namespace MyApp.Common
{
public static class MyExtensions{
public static SelectList ToSelectList(this TEnum enumObj)
where TEnum : struct, IComparable, IFormattable, IConvertible
{
var values = from TEnum e in Enum.GetValues(typeof(TEnum))
select new { Id = e, Name = e.ToString() };
return new SelectList(values, "Id", "Name", enumObj);
}
}
}This allows you to write:
ViewData["taskStatus"] = task.Status.ToSelectList();by
using MyApp.CommonCode Snippets
@Html.EnumDropDownListFor(
x => x.YourEnumField,
"Select My Type",
new { @class = "form-control" })@Html.DropDownList("MyType",
EnumHelper.GetSelectList(typeof(MyType)) ,
"Select My Type",
new { @class = "form-control" })namespace MyApp.Common
{
public static class MyExtensions{
public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
where TEnum : struct, IComparable, IFormattable, IConvertible
{
var values = from TEnum e in Enum.GetValues(typeof(TEnum))
select new { Id = e, Name = e.ToString() };
return new SelectList(values, "Id", "Name", enumObj);
}
}
}ViewData["taskStatus"] = task.Status.ToSelectList();Context
Stack Overflow Q#388483, score: 907
Revisions (0)
No revisions yet.