Home >Backend Development >C++ >How to Create a DropdownList from an Enum in ASP.NET MVC?
Html.DropDownList
expansion method in ASP.NET MVC provides a way to facilitate creating a drop -down list. However, using it with enumeration may be tricky.
Html.EnumDropDownListFor
MVC 5.1 introduced the Html.EnumDropDownListFor
extension method, simplifying the process of creating a drop -down list from enumeration. Examples as follows:
<code class="language-csharp">@Html.EnumDropDownListFor( x => x.YourEnumField, "请选择类型", new { @class = "form-control" })</code>MVC version 5: Use
EnumHelper
category: Microsoft.Web.Mvc.dll
in the EnumHelper
program concentration
<code class="language-csharp">@Html.DropDownList("MyType", EnumHelper.GetSelectList(typeof(MyType)) , "请选择类型", new { @class = "form-control" })</code>MVC 5 and below versions: Use the extension method
: SelectList
<code class="language-csharp">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); } } }</code>This allows you to use the
Method: ToSelectList
<code class="language-csharp">ViewData["taskStatus"] = task.Status.ToSelectList();</code>
The above is the detailed content of How to Create a DropdownList from an Enum in ASP.NET MVC?. For more information, please follow other related articles on the PHP Chinese website!