C# 使用带有Html.DropDownList的ViewBag获取强制转换错误

C# 使用带有Html.DropDownList的ViewBag获取强制转换错误,c#,asp.net-mvc,C#,Asp.net Mvc,我试图使用ViewBag来填充Html.DropDownList方法,但当我这样做时,我得到了错误: 无法将类型为“System.Collections.Generic.List1[f_uAnonymousType02[System.Int16,System.String]]”的对象强制转换为类型为“System.Web.Mvc.SelectList” 我确信这是因为在填充视图包时使用了AnyonymousType,但我不确定如何将ViewBag设置为SelectList 使用(CoreSite

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

无法将类型为“System.Collections.Generic.List
1[f_uAnonymousType0
2[System.Int16,System.String]]”的对象强制转换为类型为“System.Web.Mvc.SelectList”

我确信这是因为在填充
视图包时使用了
AnyonymousType
,但我不确定如何将
ViewBag
设置为
SelectList

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

@Html.DropDownList(“Sections”,(SelectList)ViewBag.Sections,“--selectsection--”


我应该如何设置我的ViewBag以使其正常工作?

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

既然您没有将该
SelectList
分配给
ViewBag
,那么如何向上传递该
SelectList
?添加了一行额外内容,将SelectList添加到
ViewBag
很高兴提供帮助!“如果答案确实是正确的,别忘了把它标记为正确答案。”坎布吕斯刚刚做了,在我能做之前,他不得不等待时间列表过去。