Creating dropdownlist in asp.net mvc using enum. Using enum we can populate dropdown list with selectlistitem in mvc. see below example with all steps:
Inside model we need to define
- a property of enum type.
- a property of SelectedListItem as IEnumerable.
- Inside constructor filling Dropdown list from enum.
Model
- public class UserModel
- {
- public Country Country { get; set; }
- public IEnumerable<SelectListItem> CountryList { get; set; }
- public UserModel()
- {
- CountryList = Enum.GetNames(typeof(Country)).Select(name => new SelectListItem()
- {
- Text = name,
- Value = name
- });
- }
- }
Enum (County list)
- public enum Country
- {
- India,
- USA,
- UK,
- Canada
- }
Action (Creating object of model and return model)
- public class HomeController : Controller
- {
- public ActionResult Country()
- {
- UserModel model = new UserModel();
- return View(model);
- }
- }
View (Calling mode on top and filling dropdown list)
- @model MvcApplication1.Models.UserModel
-
- @{
- ViewBag.Title="Country DropDown"
- Layout="~/Views/Shared/_Layout.cshtml"
- }
-
- Country:
- @Html.DropDownListFor(model=>model.Country, Model.CountryList)