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:
@Html.EnumDropDownListFor( x => x.YourEnumField, "请选择类型", new { @class = "form-control" })
EnumHelper
category: Microsoft.Web.Mvc.dll
in the EnumHelper
program concentration
@Html.DropDownList("MyType", EnumHelper.GetSelectList(typeof(MyType)) , "请选择类型", new { @class = "form-control" })
: SelectList
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); } } }
Method: ToSelectList
ViewData["taskStatus"] = task.Status.ToSelectList();
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!