RunningEXE RunningEXE - 1 month ago 9
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

GetAssignedToDDL
that is of type
List<SelectListItem>
.

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'
to
'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
List<SelectListItem
? 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
}).ToList();

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

It sounds like you should be able to 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.

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