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
Release: 2025-01-31 11:11:10
Original
456 people have browsed it

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:

@Html.EnumDropDownListFor(
    x => x.YourEnumField,
    "请选择类型", 
    new { @class = "form-control" })
Copy after login
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

@Html.DropDownList("MyType", 
   EnumHelper.GetSelectList(typeof(MyType)) , 
   "请选择类型", 
   new { @class = "form-control" })
Copy after login
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

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);
        }
    }
}
Copy after login
This allows you to use the

Method: ToSelectList

ViewData["taskStatus"] = task.Status.ToSelectList();
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template