我使用下面的代碼與我的MVC HTML視圖下拉列表曹景偉錯誤
@Html.DropDownListFor(m => m.Company,
new SelectList(ViewBag.Companies, "Key", "Value", Model.Company))
我的控制器使得這樣的:
[HttpGet]
public ActionResult Login()
{
ViewBag.Companies = (from a in _context.Companies
select new {Key = a.Id, Value = a.Name});
return View();
}
但是顯示了以下錯誤:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 30: Line 31: Line 32:
@Html.DropDownListFor(m => m.Company, Line 33: new SelectList(ViewBag.Companies, "Key", "Value", Model.Company)) Line 34:
此代碼用於在登錄屏幕上顯示公司的用戶名,密碼和下拉菜單。
你認爲什麼是@模型?在你的Controller動作中,你需要將一個實例傳遞給'View()',例如:'Return View(new YourModel());'... – nemesv
,但它可以很好地用於例如顯示基於該模型?只是不下拉? – LmC
它不起作用,因爲你正在訪問你的助手中的Model.Company,而你的'Model'是空的。只要編寫'@ Html.DropDownListFor(m => m.Company, new SelectList(ViewBag.Companies,「Key」,「Value」))' – nemesv