Home >Backend Development >C++ >How to Populate a Razor DropdownList from a List in MVC?
Populating a Razor Dropdownlist from a List
To populate a dropdownlist with data from a List
Creating a Viewmodel
Create a viewmodel with the necessary properties to drive the dropdownlist, such as a property for the selected value and a list of items for display. In this case, we'll call it UserRoleViewModel.
Preparing the DropDownList Data
Within your controller, construct a method to retrieve the data for your dropdownlist. In this method, you can transform the data from the List
Consuming the Viewmodel in the View
In your view, utilize the @model directive to access the UserRoleViewModel. Then, use the Razor helpers LabelFor and DropDownListFor to render the dropdownlist and its label. The DropDownListFor helper will automatically populate the dropdownlist with the UserRoles collection defined in the viewmodel.
Example Implementation
Here's an example implementation for the viewmodel, controller, and view:
ViewModel:
public class UserRoleViewModel { public int SelectedUserRoleId { get; set; } public IEnumerable<SelectListItem> UserRoles { get; set; } }
Controller:
public 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)
By following this approach, you can effectively populate a dropdownlist with data from a List
The above is the detailed content of How to Populate a Razor DropdownList from a List in MVC?. For more information, please follow other related articles on the PHP Chinese website!