Many times in an application we need to populate a dropdown list from enum.In the following article
I will show how to implement the same using SelectListItem.
First we create an enum, FileType, under the Models folder as shown below.
namespace DropdownDemo.Models
{
public enum FileType
{
Excel=1,
PDF=2,
TXT=3
}
}
Now we create View (Index.cshtml) as below.
@model DropdownDemo.Models.ActionModel
@{
ViewBag.Title = "Index";
}
@Html.LabelFor(model=>model.ActionId)
@Html.DropDownListFor(model=>model.ActionId, Model.ActionsList)
Next we create a list from an enum and add a model as below.
public class ActionModel
{
public ActionModel()
{
ActionsList = new List<SelectListItem>();
}
[Display(Name="Actions")]
public int ActionId { get; set; }
public IEnumerable<SelectListItem> ActionsList { get; set; }
}
Lastly we create a controller action method in Action Controller (ActionController.cs) that returns a
view that binds with the model.
public ActionResult Index()
{
ActionModel model = new ActionModel();
IEnumerable<FileType> fileTypes = Enum.GetValues(typeof(FileType)).Cast<FileType>();
model.ActionsList = from file in fileTypes
select new SelectListItem
{
Text = file.ToString(),
Value = file.ToString()
};
return View(model);
}
When the above code is executed the enum items will be populated in the dropdown.
0 Comment(s)