In the previous article we looked at how to populate dropdownlist in MVC
Enum type in C# is used to declare set of named constants.Named constants are required in any application.For example we can have different priorities such as trivial,critical and non critical.Another example of named constants are the different colors.
To represent these constant values Enum type is used.We declare enum as:
public enum Colors { RED, BLUE, GREEN, }
Since dropdownlist in mvc also represents a list of values so Enum type is well suited for populating dropdown.
For populating dropdown using enum an important enum method is used , GetValues.
The GetValues method returns an array containing the values in the specified enum type.
for example we can call the GetValues method and pass the above enum type as an argument
Colors[] values = (Colors[])Enum.GetValues(typeof(Colors));
The values contained by the above values array will be the different enum values.
values[0] RED
values[1] BLUE
values[2] GREEN
The type of the values contained by the above values array will be Enum
In the array returned by the above method we can get the name of the enum values using the toString() method.So if we call toString() on the different values in the array then we will get
values[0] “RED”
values[1] “BLUE”
values[2] “GREEN”
So to populate the dropdown using the enum we need to do the following steps
1.Declare an enum type which represents the values we want to populate in the dropdown
public enum Colors { RED, BLUE, GREEN, }
2.Call Enum.GetValues(typeof(EnumType)), EnumType is the type of Enum we declared in the above step
Colors[] values = (Colors[])Enum.GetValues(typeof(Colors));
3. Iterate through the above array and populate SelectList
To Populate dropdown with enum in mvc we can use a simple Linq query.We create SelectListItems with the array returned by the GetValues method.
var colors = from item in values select new SelectListItem() { Text = item.ToString(), Value = ((int)item).ToString(), };
4. Set the ViewData or ViewBag value equal to above array
ViewBag.colors = colors;
5. Call @Html.DropDownList(“key”) and pass the key set in in ViewBag ,in the action method.
@Html.DropDownList("colors")
If we follow the above steps the dropdown rendered will be populated with the Enum values.
Leave a Reply