Home > Backend Development > C++ > How to Populate a DropDownList with Enum Values in ASP.NET MVC?

How to Populate a DropDownList with Enum Values in ASP.NET MVC?

Susan Sarandon
Release: 2025-01-31 11:16:13
Original
591 people have browsed it

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 For MVC V5.1 (and higher version):

Use Method:

For MVC V5 (and lower versions): Html.EnumDropDownListFor

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

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

Remember to contain

naming space to use this expansion method.
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

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!

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