我在視圖上有一個下拉串列,該視圖將用戶添加到資料庫中。下拉串列代碼目前在用戶控制器的CreateUser()方法中,并且可以完美運行。我需要在整個應用程式中重用此代碼,因此我創建了一個名為 stores 的新類,并創建了一個名為LoadStoreList()的方法,并將代碼從 CreateUser() 移到了這個新方法中。這個想法顯然是每次我需要用商店串列填充下拉串列時呼叫這個 LoadStoreList() 方法。
控制器 我想從 CreateUser() 方法呼叫 LoadStoreList() 方法。
public IActionResult CreateUser()
{
var getStoreList = new Stores();
ViewBag.Stores = getStoreList.LoadStoreList();
return View();
}
專賣店類
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;
}
}
我遇到的問題是 LoadStoreList 方法中的 storeList 物件始終為 null ,我看不出哪里出錯了。
編輯
private static ApplicationDbContext _context;
public Stores()
{
_context = new ApplicationDbContext();
}
uj5u.com熱心網友回復:
試試:
1.對您的控制器進行一些更改(用您的控制器替換 LoopDroController):
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.更改您的商店,如下所示:
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.結果:
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/527204.html