Home >Backend Development >C++ >How to Create a DropdownList from an Enum in ASP.NET MVC?

How to Create a DropdownList from an Enum in ASP.NET MVC?

Susan Sarandon
Susan SarandonOriginal
2025-01-31 11:11:10431browse

Create a drop -down list from an enumeration 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.

MVC 5.1 and above versions: Use 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

If you are using MVC 5, you can use the

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

For the previous version of MVC 5, you can create an extension method to convert to

: 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn