I want to create a dropdown with C#, ASP.NET Core that will be displayed in the view and get the information of the dropdown list from the database and display it in the view. How can I do this?
While the selectListItem
in the space there is a name that is obsolete.
public class AddUserRoleDto
{
public string Id { get; set; }
public string Role { get; set; }
public List<SelectListItem> Roles{ get; set; }
}
public IActionResult AddUserRole(string Id)
{
var role = new List<SelectListItem>(
_roleManager.Roles.Select(p => new SelectListItem
{
Text = p.Name,
Value = p.Name
}).ToList());
return View(new AddUserRoleDto
{
Id = Id,
Roles = role,
});
}
I want to create a dropdown with C#, ASP.NET Core that will be displayed in the view
In the AddUserRole, you can use ViewBag to pass the SelectList to the view:
public IActionResult AddUserRole(string Id)
{
//do your staff
ViewBag.Roles = new SelectList(_roleManager.Roles, "Name", "Name");
}
Then in the view use asp-items :
<select name="Roles" class="form-control" asp-items="@ViewBag.Roles"></select>