5

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://i.sstatic.net/pwreR.jpg

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" />
0

1 Answer 1

21

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.