Tuesday, April 5, 2016

DropDownList In MVC

This post will explain you the different ways of binding the dropdownlist in ASP.NET MVC razor view engine.

Bind DropDownList with the static values.


@Html.DropDownList("Role", new List<SelectListItem>(){new SelectListItem(){ Text= "Admin", Value = "1"},new SelectListItem(){ Text= "Guest", Value = "2"},}, "Please Select", new { @class = "form-control" })

Bind DropDownList with ViewData/ViewBag values.

In controller index method the List<SelectListItem> are added and assigned to ViewBag.
public ActionResult Index()
{
List<SelectListItem> roles = new List<SelectListItem>();
roles.Add(new SelectListItem { Text = "Admin", Value = "1" });
roles.Add(new SelectListItem { Text = "Guest", Value = "2" });
ViewBag.Role = roles;
return View();
}
You can render the dropdownlist as below. Dropdownlist helper will have many overloading methods with different parameters.
@Html.DropDownList("Role", null, "All", new { @class = "control-label" })
OR
@Html.DropDownList("Role")

No comments:

Post a Comment