将ViewBag与Html一起使用.DropDownList获取Cast错误

本文关键字:DropDownList 获取 Cast 错误 ViewBag Html 一起 | 更新日期: 2023-09-27 18:04:26

我正试图使用ViewBag来填充Html.DropDownList方法,但当我这样做时,我会得到错误:

无法强制转换类型为"System"的对象。集合。通用的列出1[<>f__AnonymousType0 2[System.Int16,System.String]]'以键入'System。网状物Mvc。选择列表。

我确信这是由于在填充ViewBage时使用了AnyonymousType,但我不确定如何将ViewBag设置为SelectList

using (CoreSiteContext db = new CoreSiteContext()) { ViewBag.Sections = db.Sections .Select(s => new { s.ID, s.Title }) .ToList(); }

@Html.DropDownList("Sections", (SelectList) ViewBag.Sections, "--Select Section--")

我究竟应该如何设置ViewBag才能使其工作?

将ViewBag与Html一起使用.DropDownList获取Cast错误

您错误地使用了SelectList-您试图将匿名类型强制转换为SelectList,这是行不通的。以下是正确的用法:

using (CoreSiteContext db = new CoreSiteContext())
{
    var items = db.Sections
                  .Select(s => new { s.ID, s.Title })
                  .ToList();
    var selectList = new SelectList(items, "ID", "Title");
    ViewBag.Sections = selectList;
}