2016-12-02 67 views
0

我剛剛在堆棧溢出中創建了我的帳戶,所以這是我第一次問一個問題:我的DropDownList有問題。我不知道我做錯了,因爲我是比較新的ASP-NET和MVC 5,所以請原諒任何可怕的事情我做DropDownListFor:no類型爲'IEnumerable <SelectListItem>'的具有密鑰的ViewData項目

控制器:

public ActionResult typeDevices() 
    { 
     List<SelectListItem> typelist = new List<SelectListItem>(); 
     DropDownModel type = new DropDownModel(); 


     type.TypeDevicesId = 1; 
     type.TypeDevicesValue = "typeDevice1"; 

     typelist.Add(new SelectListItem() { Value = type.TypeDevicesValue, Text = type.TypeDevicesId.ToString() }); 

     type.TypeDevicesId = 2; 
     type.TypeDevicesValue = "typeDevice2"; 

     typelist.Add(new SelectListItem() { Value = type.TypeDevicesValue, Text = type.TypeDevicesId.ToString() }); 

     type.TypeDevicesId = 3; 
     type.TypeDevicesValue = "typeDevice3"; 

     typelist.Add(new SelectListItem() { Value = type.TypeDevicesValue, Text = type.TypeDevicesId.ToString() }); 

     SelectList listvalues = new SelectList(typelist, "Text", "Value"); 
     ViewBag.DropDownValues = listvalues; 
     ViewData["DropDownData"] = new SelectList(listvalues, "Text", "Value"); 
     return View(); 
    } 

型號:

public class DropDownModel 
{ 
    public int TypeDevicesId { get; set; } 
    public string TypeDevicesValue { get; set; } 
} 

指數:

<p> 
    <label class="field" for="Type">Type:</label> 
    @Html.DropDownList("DropDownData", (SelectList)ViewBag.DropDownValues)) 
</p> 

此代碼來自我是以下的視頻。 Link to video

的錯誤,我得到的是

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'DropDownData'

+0

從第一個創建第二個相同的'SelectList'是沒有意義的額外開銷 - 它只是'ViewBag.DropDownValue = typelist;'而且你不能綁定'IEnumerable '''所以'ViewData [「DropDownData 「] = new SelectList(listvalues,」Text「,」Value「);'沒有任何意義。它的'ViewData [「DropDownData」] = 2;'如果你想要選擇第二個選項。但你的代碼是可怕的做法,我建議你閱讀[這個問題/答案](http://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of- type-system-int32-but-must-o-o) –

+0

感謝您的建設性批評,我會看看:) 出於好奇,如果我想從數據庫中取一個項目,我該怎麼辦? 可以說type_devices與表computers_tabel有關係。 我希望它選擇與計算機ID相關的正確一個? – FllnAngl

+0

我給你的鏈接展示瞭如何去做:) –

回答

0

的問題解決了,我做了一個公開的ActionResult TypeDevices但我從來沒有叫吧。所以這有點愚蠢。感謝大家的幫助! :)

我通過在ActionResult索引中更改Public ActionResult TypeDevicesPublic void Type Devices並將其稱爲TypeDevices();解決了該問題。

0

這行代碼只是改變

ViewBag.DropDownValues = listvalues; 

ViewBag.DropDownValues = typelist; 

您需要提供IEnumerable<SelectListItem>類型的數據到您的落下。您的listvalues類型爲SelectList,但您的typelist是必需的類型。

+0

謝謝,但它沒有奏效,我仍然收到錯誤:其他信息:沒有類型爲'IEnumerable '的ViewData項具有'DropDownData'鍵。 它可能與@ Html.DropDownList(「DropDownData」)有關,也許它應該是DropDownValues? – FllnAngl

0

試試這個:

ViewData["DropDownData"] = typelist; 
@Html.DropDownList("DropDownData", (List<SelectListItem>)ViewData["DropDownData"]) 
+0

謝謝,但不幸的是,也沒有工作。我開始認爲DropDownLists只是不喜歡我:P – FllnAngl

+0

請分享錯誤屏幕。 – codelover

+0

鏈接到錯誤屏幕圖像:http://prntscr.com/dehawf – FllnAngl

相關問題