A dropdownlist in MVC is a collection of SelectListItem objects. Depending on your project requirement you may either hard code the values in code or retrieve them from a database table. In this tutorial, I will show you how to generate a dropdownlist using DropDownList html helper based on both approaches.
Generating a DropDownList using Hard Coded Values
You will use the following overloaded version of "DropDownList" HTML helper.
DropDownList(string name, IEnumerable<SelectListItem> selectList, string optionLabel)
The following code will generate a departments dropdown list. The first item in the list will be "Select Department".
@Html.DropDownList("Departments", new List<SelectListItem>
{
new SelectListItem { Text = "IT", Value = "1", Selected=true},
new SelectListItem { Text = "HR", Value = "2"},
new SelectListItem { Text = "Payroll", Value = "3"}
}, "Select Department")
The downside of hard coding dropdownlist values with-in code is that, if we have to add or remove departments from the dropdownlist, the code needs to be modified.
Retrieve DropDownList from A Database Table
Pass list of Departments from the controller, then store them in "ViewBag"
public ActionResult Index()
{
// Connect to the database
SampleDBContext db = new SampleDBContext();
// Retrieve departments, and build SelectList
ViewBag.Departments = new SelectList(db.Departments, "Id", "Name");
return View();
}
Now in the "Index" view, you can access Departments list from "ViewBag"
@Html.DropDownList("Departments", "Select Department")
HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.