You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTMLDropDownListFor按MemoId过滤遇CS1977错误求助

解决DropDownListFor过滤时的CS1977错误

错误原因

ViewBag是dynamic类型,直接在ViewBag.lstSacntion上使用Lambda表达式的Where方法时,编译器无法提前确定集合的具体类型,因此触发CS1977错误——动态分发操作不能使用Lambda表达式作为参数。

解决办法

方法一:在控制器中提前过滤集合(推荐)

将数据过滤逻辑放在控制器中,符合MVC分层设计思想,视图仅负责展示数据:

// 控制器代码示例
// 假设原集合为lstSacntion,过滤出MemoId=0的项
var filteredSacntions = lstSacntion.Where(item => item.MemoId == 0).ToList();
// 将过滤后的集合存入ViewBag
ViewBag.FilteredSacntions = filteredSacntions;

视图中直接使用过滤后的集合:

@Html.DropDownListFor(model => model.MemoTeplateId, new SelectList(ViewBag.FilteredSacntions,"Id", "Name"), "-- Select Disciplinary --", new { @class = "form-control col-md-12" })

方法二:在视图中强转集合后再过滤

如果必须在视图中处理,先将ViewBag中的集合强转为具体类型,再执行过滤:

@{
    // 替换YourEntityType为集合元素的实际类型(比如Sacntion)
    var originalList = ViewBag.lstSacntion as List<YourEntityType>;
    // 过滤并处理空集合情况
    var filteredList = originalList?.Where(item => item.MemoId == 0).ToList() ?? new List<YourEntityType>();
}

@Html.DropDownListFor(model => model.MemoTeplateId, new SelectList(filteredList,"Id", "Name"), "-- Select Disciplinary --", new { @class = "form-control col-md-12" })

内容的提问来源于stack exchange,提问作者Ray Jay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 08:55:21