I have a problem with a dropdownlist. It's always empty,even though when debugging there is 4 different entries in the list that's set in asp-items as follows:
What am I doing wrong?
ViewModel:
public IEnumerable<SelectListItem> SelectRole { get; set; }
public string RoleId { get; set; }
Controller:
model.SelectRole = _roleManager.Roles?.Select(s => new SelectListItem
{
Value = s.Id,
Text = s.Name
});
View:
<select asp-for="RoleId" asp-items="@Model.SelectRole" class="form-control" />
Problem is that you are using self closing select
tag as follows:
<select asp-for="RoleId" asp-items="@Model.SelectRole" class="form-control" />
It would not generate the select list properly.
You can tune your code as follows:
In the ViewModel:
public SelectList RoleSelectList { get; set; }
public string RoleId { get; set; }
In the controller method:
var roleList = _roleManager.Roles.Select(r => new {r.Id, r.Name}).ToList();
model.RoleSelectList = new SelectList(roleList, "Id","Name");
In the View:
<select asp-for="RoleId" asp-items="Model.RoleSelectList" class="form-control">
<option value="">Select Role</option>
</select>
Now everything should work fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.