Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating dropdownlist in ASP.NET Core

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" />
like image 919
Supernalle Avatar asked Jan 20 '19 16:01

Supernalle


1 Answers

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.

like image 132
TanvirArjel Avatar answered Oct 02 '22 01:10

TanvirArjel