Home >Backend Development >C++ >How to Populate a DropDownList with Enum Values in ASP.NET MVC?
In the ASP.NET MVC, use the enumeration value to fill the drop -down list
Create a drop -down list with enumerated value in ASP.NET MVC, which can be easily implemented using the
expansion method. To use this method with enumeration, follow the following steps:
Html.DropDownList
Use Method:
Html.EnumDropDownListFor
<code class="language-csharp">@Html.EnumDropDownListFor( x => x.YourEnumField, "请选择类型", new { @class = "form-control" } )</code>Use Class:
If you are using MVC 5 or lower versions, you can use the expansion method to expand the RUNE solution:
EnumHelper
This allows the use of simple syntax:
<code class="language-csharp">@Html.DropDownList("MyType", EnumHelper.GetSelectList(typeof(MyType)), "请选择类型", new { @class = "form-control" } )</code>
Remember to contain
naming space to use this expansion method.<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>
The above is the detailed content of How to Populate a DropDownList with Enum Values in ASP.NET MVC?. For more information, please follow other related articles on the PHP Chinese website!