Attention! This is a question: How do you create a dropdownlist from an enum in ASP.NET MVC?

I want to create a Html.DropDownList drop-down list based on my enumeration:

 public enum ItemTypes { Movie = 1, Game = 2, Book = 3 } 

How do I implement this?

1 answer 1

In MVC v5.1, use Html.EnumDropDownListFor

 @Html.EnumDropDownListFor( x => x.YourEnumField, "Select My Type", new { @class = "form-control" }) 

Also in this version the Display attribute is supported: you can add [Display(Name = "Sample")] attributes to each enumeration value and the same code will list your messages in the drop-down list.

For MVC v5 use EnumHelper

 @Html.DropDownList("MyType", EnumHelper.GetSelectList(typeof(MyType)) , "Select My Type", new { @class = "form-control" }) 

For MVC 5 and below

Use the following extention:

 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); } } } 

This will allow you to write like this:

 ViewData["taskStatus"] = task.Status.ToSelectList(); 
  • one
    This is fine, but in the case of any other language (not English), a problem arises - a direct transfer of values ​​from Enum is no good, we need a translation. How to be? Add an example for the Russian language? - Bulson