I'm trying to populate a dropdown list in my Razor page. To do this, I created a view model that will have a list of users. The list of users needs to be populated from IdentityDbContext
.
I'm going through all the examples posted by other users and the issue I'm having is defining the correct variables.
Startup.cs
services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(_config.GetConnectionString("DefaultConnection")));
AppDbContext.cs
public class AppDbContext : IdentityDbContext<ApplicationUser>
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
}
ProcessCreateViewModel.cs
public IEnumerable<ApplicationUser> Users { get; set; }
public string User { get; set; }
ProcessController.cs
public IActionResult CreateProcess()
{
var context = new AppDbContext();
var processCreateViewModel = new ProcessCreateViewModel()
{
Users = context.Users.ToList()
};
return View(processCreateViewModel);
}
CreateProcess.cshtml
<div class="form-group">
@Html.LabelFor(x => Model.User, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-5">
@Html.DropDownListFor(x => Model.User, new SelectList(Model.Users, "Value", "Text"), htmlAttributes: new { @class = "form-control", id = "ApplicationUser" })
@Html.ValidationMessageFor(x => x.User, "", new { @class = "text-danger" })
</div>
</div>
The issue I'm experiencing is that the line in ProcessController.cs
,
var context = new AppDbContext();
return an error:
There is no argument given that corresponds to the required formal parameter 'options'
I have no idea how to fix or change my approach to get the user loaded into a list on my ViewModel so that I can use it in a dropdown list on my page.
You need to add it like this: services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(_config.GetConnectionString("DefaultConnection")));
As well why are you initializing a new isntance of DB context, you need to dependecy inject the Db context, as you are initializing it for DI with this line services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(_config.GetConnectionString("DefaultConnection")));
, then everything should be fine, for example:
public class YourController {
public YourController (YourDbContext context){
//.. Assign here and then reuse in controller end points
}
}
Otherwise you are trying to initialize the DBContext yourself and the DbContext as it says does not have a default constructor to address to.