Populating Razor DropDownList with a List
In this scenario, we have a model containing a List
To populate a dropdownlist, a viewmodel (UserRoleViewModel) can be introduced to separate business logic and simplify the view. This viewmodel includes SelectedUserRoleId for user selection and a list (UserRoles) for dropdown items.
Controller:
View:
Example:
Viewmodel:
public class UserRoleViewModel { [Display(Name = "User Role")] public int SelectedUserRoleId { get; set; } public IEnumerable<SelectListItem> UserRoles { get; set; } }
Controller:
private IEnumerable<SelectListItem> GetRoles() { var dbUserRoles = new DbUserRoles(); var roles = dbUserRoles .GetRoles() .Select(x => new SelectListItem { Value = x.UserRoleId.ToString(), Text = x.UserRole }); return new SelectList(roles, "Value", "Text"); } public ActionResult AddNewUser() { var model = new UserRoleViewModel { UserRoles = GetRoles() }; return View(model); }
View:
@model UserRoleViewModel @Html.LabelFor(m => m.SelectedUserRoleId) @Html.DropDownListFor(m => m.SelectedUserRoleId, Model.UserRoles)
This approach results in a dropdownlist populated with the values from the DbUserRoles list.
The above is the detailed content of How to Populate a Razor DropDownList with a List in MVC?. For more information, please follow other related articles on the PHP Chinese website!