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

时间:2014-05-21 22:05:43

标签: c# asp.net-mvc

我正在尝试使用ViewBag填充Html.DropDownList方法,但是当我这样做时,我收到错误:

  

无法转换类型&System; System.Collections.Generic.List 1[<>f__AnonymousType0 2 [System.Int16,System.String]]&#39;输入&#39; System.Web.Mvc.SelectList&#39;。

我确信这是因为在填充AnyonymousType时使用了ViewBage,但我不确定如何将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以使其正常工作?

1 个答案:

答案 0 :(得分:1)

您使用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;
}