"Creating a DropDownList from an Enum in ASP.NET MVC"
In this article I will try to explain, how can we bind an Enum to a DropDownList in ASP.NET MVC.
Let us understand it with the help of an example:
Step 1: Create an Asp.Net MVC Application.
Step 2: Create a new class and write an enum (say "ActionType").
Example:
public enum ActionType
{
Create = 1,
Read = 2,
Update = 3,
Delete = 4
}
Step 3: Now inside the Model create a class (say "ActionModel") and write the code as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MultipleSubmit.Models
{
public class ActionModel
{
public ActionModel()
{
ActionsList = new List<SelectListItem>();
}
[Display(Name = "Actions")]
public int ActionId { get; set; }
public IEnumerable<SelectListItem> ActionsList { get; set; }
}
}
In the above code we have two properties one of int type with display name= "Actions" and another is a Collection of type <SelectListItem>.
Step 4: Now go to the controller and write the following code:
public ActionResult Index()
{
ActionModel model = new ActionModel();
IEnumerable<MultipleSubmit.Models.MultipleSubmittAttribute.ActionType>
actionTypes = Enum.GetValues(typeof(MultipleSubmit.Models.MultipleSubmittAttribute
.ActionType)).Cast<MultipleSubmit.Models.MultipleSubmittAttribute.
ActionType>();
model.ActionsList = from action in actionTypes
select new SelectListItem
{
Text = action.ToString(),
Value = ((int)action).ToString()
};
return View(model);
}
In the above code we first instantiate the ActionModel Class. Then create a Collection of the defined Enum Type and populate it with the defined Enum.Then from this Collection we populate the ActionsList of type defined in the Model Class with Text, Value pair.
Step 5: Now go to the View and write the following Razor code:
@model MultipleSubmit.Models.ActionModel
@{
ViewBag.Title = "Index";
}
<div>
@Html.LabelFor(model => model.ActionId)
@Html.DropDownListFor(model => model.ActionId, Model.ActionsList)
</div>
The Line:
@Html.DropDownListFor(model => model.ActionId, Model.ActionsList)
Will create a DropDown by binding ActionsList declared in the Model to the DropDown. The Model was passed from the Controller to the View.
Step 6: Now build the Application and run, You will get the following Output:
Hope it helps...Happy Coding !
0 Comment(s)