Home > Backend Development > C++ > How to Populate a Razor DropDownList with a List in MVC?

How to Populate a Razor DropDownList with a List in MVC?

DDD
Release: 2024-12-29 22:44:33
Original
697 people have browsed it

How to Populate a Razor DropDownList with a List in MVC?

Populating Razor DropDownList with a List in MVC

In this scenario, we have a model containing a List, namely DbUserRoles GetRoles() method, and a Controller that loads the view while passing the retrieved list as a model.

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:

  • Transform the DbUserRoles list into a suitable form for presentation (SelectListItem list) using LINQ Select.

View:

  • Use @Html.LabelFor and @Html.DropDownListFor to bind the viewmodel properties to the corresponding HTML elements.

Example:

Viewmodel:

public class UserRoleViewModel
{
    [Display(Name = "User Role")]
    public int SelectedUserRoleId { get; set; }
    public IEnumerable<SelectListItem> UserRoles { get; set; }
}
Copy after login

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);
}
Copy after login

View:

@model UserRoleViewModel

@Html.LabelFor(m => m.SelectedUserRoleId)
@Html.DropDownListFor(m => m.SelectedUserRoleId, Model.UserRoles)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template