2013-08-23 61 views
2

在我看來,我有一個DropDownList,它使用數據庫數據填充。但是當我運行它時,出現一個我不太明白的錯誤:使用數據庫數據填充DropDownList時出錯

「沒有ViewData項的類型'IEnumerable'具有'DdlBagTypes'鍵。

我不知道如何做到這一點,但我擡頭各種解決方案,這是我要做的事:

函數從數據庫中獲取數據:

public IEnumerable<SelectListItem> getBagelTypes() 
    { 
     return (from t in Db.BagelType.AsEnumerable() 
       select new SelectListItem 
       { 
        Text = t.Name, 
        Value = t.BagelTypeId.ToString(), 
       }).AsEnumerable();    
    } 

控制器:

public ActionResult Index() 
    { 
     ViewData["LstBagels"] = DbO.getBagels(); 
     TempData["LstTypeOptions"] = DbO.getBagelTypes(); 
     Session["OrderCount"] = OrderCount; 

     return View(); 
    } 

查看:

@model BestelBagels.Models.Bagel 
@{ 
ViewBag.Title = "Home Page"; 

var LstBagels = ViewData["LstBagels"] as List<BestelBagels.Models.Bagel>; 
var LstTypeOptions = TempData["LstTypeOptions"] as IEnumerable<SelectList>; 
var OrderCount = Session["OrderCount"]; 
} 

@Html.DropDownList("DdlBagTypes", (SelectList)LstTypeOptions) 
+2

這一個讓我所有 時間。檢查'LstTypeOptions'是否爲'null' – CodingIntrigue

回答

3

相反的TempData的使用的ViewData將數據傳遞給視圖:

ViewData["LstTypeOptions"] = DbO.getBagelTypes(); 

和內部視圖:

var LstTypeOptions = ViewData["LstTypeOptions"] as IEnumerable<SelectListItem>; 

然後:

@Html.DropDownList("DdlBagTypes", LstTypeOptions) 

還要注意正確的類型被鑄造IEnumerable<SelectListItem>這就是你的getBagelTypes函數返回的結果。在你的例子中,你試圖投向IEnumerable<SelectList>,這顯然返回null,因爲這不是你存儲在TempData裏面的東西。

但我個人會扔掉這個ViewData的東西,引進視圖模型:

public class MyViewModel 
{ 
    public string SelectedOption { get; set; } 
    public IEnumerable<SelectListItem> LstTypeOptions { get; set; } 

    public string SelectedBagel { get; set; } 
    public IEnumerable<SelectListItem> LstBagels { get; set; } 

    public int OrderCount { get; set; } 
} 

,我會填充在我的控制器行動,並傳遞給視圖:

public ActionResult Index() 
{ 
    var model = new MyViewModel(); 
    model.LstTypeOptions = DbO.getBagelTypes(); 
    model.LstBagels = DbO.getBagels(); 
    model.OrderCount = OrderCount; 

    return View(model); 
} 

最後我會使我的視圖強烈鍵入視圖模型並使用強類型幫助程序:

@model MyViewModel 
... 
@Html.DropDownListFor(x => x.SelectedOption, Model.LstTypeOptions) 
@Html.DropDownListFor(x => x.SelectedBagel, Model.LstBagels) 
... 
<div>You have a total of @Html.DisplayFor(x => x.OrderCount) orders</div> 
+0

完美!非常感謝你。 –