2014-01-12 112 views
0

我使用下面的代碼與我的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:

此代碼用於在登錄屏幕上顯示公司的用戶名,密碼和下拉菜單。

+1

你認爲什麼是@模型?在你的Controller動作中,你需要將一個實例傳遞給'View()',例如:'Return View(new YourModel());'... – nemesv

+0

,但它可以很好地用於例如顯示基於該模型?只是不下拉? – LmC

+0

它不起作用,因爲你正在訪問你的助手中的Model.Company,而你的'Model'是空的。只要編寫'@ Html.DropDownListFor(m => m.Company, new SelectList(ViewBag.Companies,「Key」,「Value」))' – nemesv

回答

1

您在視圖中引用Model.Company。這將是空的,因爲它永遠不會從控制器傳遞。

+0

我明白,但它的創造情景,所以沒有任何價值。

@Html.LabelFor(model => model.Password)
@Html.EditorFor(model => model.Password) @Html.ValidationMessageFor(model => model.Password)
LmC

+0

上面的代碼工作正常。所以我不會不知道爲什麼一個下拉菜單 – LmC

+0

不同之處在於Html。「Control」對於可能的解釋器來說,模型是空的並且無論如何顯示控件。新的SelectList(ViewBag.Companies,「Key」,「Value」,Model.Company)沒有仔細檢查該級別,並在Model.Company上拋出異常。模型爲null! –

1

首先,你應該設置你的視圖模型在你的瀏覽這樣的:

@model YourClassname 

其次,你應該讓你的Company,當你返回你查看你應該通過你的項目是這樣的:

[HttpGet] 
public ActionResult Login() 
{ 
    ViewBag.Companies = (from a in _context.Companies 
        select new {Key = a.Id, Value = a.Name}); 
    // get your Company 
    var cmp = _context.Companies.First(); //for example 

    return View(cmp); 
}