Populate list of model class into DropDownList in ASP.NET MVC

Posted by Sheonarayan under ASP.NET MVC category on | Points: 40 | Views : 1960
First we need to create the list of SelectListItem from the list of Model classes.

var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Id.ToString(), Text = rr.Name }).ToList();

ViewBag.Roles = list;

Then in the View, we need to unbox the ViewBag to IEnumerable<SelectListItem>
Role Name: @Html.DropDownList("RoleName", (IEnumerable<SelectListItem>)ViewBag.Roles, "Select ...")

Hope this code snippet will be useful.

Comments or Responses

Login to post response