How do you create a dropdownlist from an enum in ASP.NET MVC?
For MVC v5.1 use Html.EnumDropDownListFor
@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<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);
}
}
}
This allows you to write:
ViewData["taskStatus"] = task.Status.ToSelectList();
by using MyApp.Common
How to create a dropdownlist from an enum in ASP.NET MVC?
In your view you can use SelectExtensions.EnumDropDownListFor:
E.g:
@Html.EnumDropDownListFor(model => model.Countries)
given that the @model
of the view has a property named Countries
that is an enum
type.
If you want to show a default text in the drop down (like: "Select country"). Take a look at the following question and answer.
Html.EnumDropdownListFor: Showing a default text
How to display Enum as DropDownList in .Net MVC Core
I figured it out with a bit of help from this source
I didn't create a helper like it suggests but I used the same principles from the helper to create a EditorTemplate for my Sizes enum. Here's what it looks like:
Sizes.cshtml
@model Options.Sizes
@{
var values = Enum.GetValues(typeof(Options.Sizes)).Cast<Options.Sizes>();
IEnumerable<SelectListItem> items =
from value in values
select new SelectListItem
{
Text = value.ToString(),
Value = value.ToString(),
Selected = (value.Equals(Options.Sizes.ATX_Full))
};
}
@Html.DropDownList("Size", items)
Now when I call @Html.EditorForModel()
in my Ball.cshtml, it references this editor template and creates a dropdown with all the options in the enum.
MVC Razor DropDownList created from Enum
You can manually build the select list as your answer shows or you can use the built in Html helper Html.EnumDropDownListFor
which will achieve what I believe you're looking for with much less code. Example usage as follows:
public class MyViewModel
{
//Month is an enum here
public Month Month { get; set; }
}
and your view (MonthExample.cshtml
) would look like :
@model MyProject.MyViewModel
...
@using(Html.BeginForm("MonthExample", "ControllerName", FormMethod.Post))
{
@Html.EnumDropDownListFor(x => x.Month)
<button type="submit">Save</button>
}
...
the framework will see that Month is an enum and automatically build the options for the dropdown list as opposed to you doing that manually.
If you'd like to see a simple example of the controller get/post, they could look like the following:
public ActionResult MonthExample()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult MonthExample(MyViewModel model)
{
//here model.Month will have the selected month from the dropdown list
}
How do you create a dropdownlist from an enum in ASP.NET MVC?
For MVC v5.1 use Html.EnumDropDownListFor
@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<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);
}
}
}
This allows you to write:
ViewData["taskStatus"] = task.Status.ToSelectList();
by using MyApp.Common
using Enum for dropdownlist in databasefirst mvc
In your view you can create the dropdown like this
Create the list from enum
like this
@{
var genderList = Enum.GetValues(typeof(Gender)).OfType<Gender>().Select(m => new { Text = m.ToString(), Value = (int)m }).ToList();
}
and create the DropDown like this
@Html.DropDownList("EmpSex", new SelectList(genderList, "Value", "Text", Model.EmpSex))
or
@Html.DropDownListFor(model => model.EmpSex, new SelectList(genderList, "Value", "Text", Model.EmpSex))
How do you create a dropdownlist from an enum in ASP.NET MVC?
For MVC v5.1 use Html.EnumDropDownListFor
@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<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);
}
}
}
This allows you to write:
ViewData["taskStatus"] = task.Status.ToSelectList();
by using MyApp.Common
Dropdownlist bound to an enum
Since my requirement was simple enough so i replaced the string. I feel there must be a better way of doing the same.
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 = Convert.ToInt32(e), Name = e.ToString().Replace('_', ' ') };
return new SelectList(values, "Id", "Name", enumObj);
}
Related Topics
Convert a Unicode String to an Escaped Ascii String
Entityframework - Contains Query of Composite Key
How to Cancel Task Await After a Timeout Period
Join/Where With Linq and Lambda
Issue With Dependencyproperty Binding
How to Create a Custom Authorizeattribute in ASP.NET Core
How to Generate a Random Integer in C#
Find All Controls in Wpf Window by Type
How to Get a Consistent Byte Representation of Strings in C# Without Manually Specifying an Encoding
Excel "External Table Is Not in the Expected Format."
Increase Upload File Size in ASP.NET Core
Benefits of Using the Conditional : (Ternary) Operator
How to Add a Timeout to Console.Readline()
Extension Method and Dynamic Object