2013-08-23 33 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

完美!非常感谢你。 –