2

在我看来,我有一个用数据库数据填充的 DropDownList。但是当我运行它时,我得到一个我不太明白的错误:

“没有具有键 'DdlBagTypes' 的 'IEnumerable' 类型的 ViewData 项。”

我不知道该怎么做,但我查找了各种解决方案,这就是我的做法:

从数据库中获取数据的函数:

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)
4

1 回答 1

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>
于 2013-08-23T14:08:13.030 回答