I have a dropdown list on a view, this view adds users to the database. The dropdown list code is currently in the CreateUser() method in the users controller, and it works perfectly. I need to reuse this code throughout the application, so I created a new Class called stores and have created a method called LoadStoreList() and have moved the code from CreateUser() to this new method. The idea is obviously to call this LoadStoreList() method every time I need to poplate a drop down with the list of stores.
Controller I want to call the LoadStoreList() method from the CreateUser() method.
public IActionResult CreateUser()
{
var getStoreList = new Stores();
ViewBag.Stores = getStoreList.LoadStoreList();
return View();
}
Stores Class
public class Stores
{
private static ApplicationDbContext? _context;
public Stores()
{
}
public Stores(ApplicationDbContext context)
{
_context = context;
}
public IActionResult LoadStoreList()
{
var storeList = _context?.Stores.Select
(s => new SelectListItem { Value = s.StoreId.ToString(), Text = s.StoreName }).ToList();
storeList?.Insert(0, new SelectListItem("-- Select --", ""));
return (IActionResult)storeList;
}
}
The issue I'm having is that the storeList object in the LoadStoreList method is always null , and I can't quite see where I'm going wrong.
Edit
private static ApplicationDbContext _context;
public Stores()
{
_context = new ApplicationDbContext();
}
CodePudding user response:
Have a try:
1.make some change to your controller(replace LoopDroController with your controller):
public class LoopDroController : Controller
{
private readonly ApplicationDbContext _context;
public LoopDroController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult CreateUser()
{
var getStoreList = new Stores(_context);
ViewBag.Stores = getStoreList.LoadStoreList();
return View();
}
}
2.change your stores like below:
public class Stores
{
private static ApplicationDbContext? _context;
public Stores(ApplicationDbContext context)
{
_context = context;
}
public List<SelectListItem> LoadStoreList()
{
ar storeList = _context?.Stores.Select
(s => new SelectListItem { Value = s.StoreId.ToString(), Text = s.StoreName }).ToList();
storeList?.Insert(0, new SelectListItem("-- Select --", ""));
return storeList;
}
}
3.result: