RunningEXE RunningEXE - 3 years ago 250
ASP.NET (C#) Question

ASP.NET - Display all Users from AspNetUsers table into Dropdown List in Identity?

After doing some research, I found ways to do what my question asks, however, I'm trying to do this inside a function called

that is of type

After trying some of the answers I found on here and other resources, I keep getting the same error. The error I keep getting:

Cannot implicitly convert type
'System.Collections.Generic.List' LWC C:\Users\runningexe\Desktop\LincolnWaterCommissionWorkOrderInventorySystem\LWC\LWC\Controllers\WorkOrderController.cs 201 Active

Is there any way to do this with the function's type being
? Or is there something else I'm missing here. Like I said, I've tried many solutions that essentially do the same thing, but the error I get is the same.

EDIT: function using Kirk's answer. Now getting an error with my DbContext.

private static List<SelectListItem> GetAssignedToDDL()
List<SelectListItem> assignedToList = new List<SelectListItem>();

var dbContext = new ApplicationDbContext();
var userList = dbContext.Users.ToList();

assignedToList = userList.Select(u => new SelectListItem
Text = u.UserName,
Value = u.Id

return assignedToList;

What I was trying before:

private static List<SelectListItem> GetAssignedToDDL()
return userManager.Users.ToList();

As well as a few other attempts with different code (Same errors). This was the most recent though.

DbContext Error:

No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

Answer Source

You can use LINQ's Select function. On the line where you see the compilation error, try appending the following:

.Select(u => new SelectListItem { Text = u.UserName, Value = u.Id }).ToList();

If you include your code, I can edit this answer to make it more specific to your use case. You will also need to include using System.Linq; if it's not already there.

If you're not familiar with Select, it's effectively known as a mapping function. You can find a good explanation here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download