2014-10-27 98 views
12

綁定在mvc下拉我總是得到這個錯誤沒有ViewData項目類型'IEnumerable'國家有關鍵我不知道如何對它進行排序沒有類型'IEnumerable <SelectListItem>'的ViewData項目,其關鍵國家

查看

@Html.DropDownList("country", 
    (IEnumerable<SelectListItem>)ViewBag.countrydrop,"Select country") 

控制器

List<Companyregister> coun = new List<Companyregister>(); 
coun = ds.getcountry(); 

List<SelectListItem> item8 = new List<SelectListItem>(); 
foreach(var c in coun) 
{ 
    item8.Add(new SelectListItem 
    { 
     Text = c.country, 
     Value = c.countryid.ToString() 
    }); 
} 

ViewBag.countrydrop = item8; 
return View(); 

我不知道我錯了,誰能幫助我在此先感謝

+0

我已更新我的代碼檢查它。 – 2014-10-27 11:07:26

+3

如果你得到這個錯誤,那麼它意味着'ViewBag.coutrydrop'的值是'null'。填充它的代碼沒有被執行,或者只有當你回發並返回視圖時(並且你還沒有再次填充'ViewBag.countrydrop') – 2014-10-27 11:08:15

+1

並考慮簡化你的代碼到'ViewBag.countrydrop = new SelectList(coun,「countryid」,「country」);''和'@ Html.DropDownList(「country」,(SelectList)ViewBag.countrydrop,...)' – 2014-10-27 11:23:03

回答

11

在你的行動改變ViewBag.countrydrop = item8ViewBag.country = item8;並鑑於這樣寫:

@Html.DropDownList("country", 
        (IEnumerable<SelectListItem>)ViewBag.country, 
        "Select country") 

其實當你寫

@ Html.DropDownList( 「國家」, (IEnumerable的)ViewBag.country, 「選擇國家」)

Html.DropDownList(「country」,「Seleclec牛逼國家)

它看起來在IEnumerable<SelectListItem>ViewBag與關鍵國家,你也可以使用此重載在這種情況下:

@Html.DropDownList("country","Select country") // it will look for ViewBag.country and populates dropdown 

Working DEMO Example

0

試試這個

@Html.DropDownList("ddlcountry",(List<SelectListItem>)ViewBag.countrydrop,"Select country") 

在控制器

ViewBag.countrydrop = ds.getcountry().Select(x => new SelectListItem { Text = x.country, Value = x.countryid.ToString() }).ToList(); 
+0

它也從來沒有工作 – 2014-10-27 10:47:29

+0

你能夠得到你的名單中的國家? – 2014-10-27 10:50:00

+0

斷點本身從來沒有打電話@ManishSharma – 2014-10-27 10:53:17

1

使用本

var list = new SelectList(countryList, "Id", "Name"); 
ViewBag.countries=list; 
@Html.DropDownList("countries",ViewBag.Roles as SelectList) 
8

如果您正在使用DropDownListFor這樣的:

@Html.DropDownListFor(m => m.SelectedItemId, Model.MySelectList) 

其中MySelectList模型是SelectList類型的屬性,這個錯誤可能會被拋出,如果財產是null

避免這種通過簡單的構造函數初始化它,就像這樣:

public MyModel() 
{ 
    MySelectList = new SelectList(new List<string>()); // empty list of anything... 
} 

我知道這不是OP的情況,但是這可能幫助像我其中有相同的錯誤緣於此。

+0

或者類似的東西: MySelectList = new List (); – Sanchitos 2017-08-07 02:51:58

+1

太常見的方式:在POST上發生錯誤,因此您將視圖模型返回到出現錯誤的頁面。但是你並沒有刷新POST中丟失的List ,所以它們是空的。而不是一個空引用,從視圖中得到一個非常誤導性的錯誤,說某些屬性不是特定類型,當你知道它完全沒有這個類型時,它應該不是這樣的。 – mmcrae 2017-08-29 14:49:34

+0

@mmcrae,我有這個問題一對夫婦時間與POST行動,在那裏我忘了再次填充我的下拉項目。 – Alisson 2017-08-29 14:59:47

0

我有一個相同的問題,我找到了解決方案,我應該把代碼從編輯方法中的數據庫檢索下拉列表。它爲我工作。

viewModel.MySelectList = new List<System.Web.Mvc.SelectListItem>(); 

由於沒有做出明確告知我現有的答案,我發佈此: Solution for the similar problem

0

在我的情況,因爲我還沒有初始化的選擇列表中的控制器是這樣發生的錯誤。也許它對任何人都有幫助。

相關問題