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:
https://imgur.com/a/CYZSO5z
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With