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

如何在ASP.NET MVC下拉列表中筛选DEPT_ID=12的测试项

如何筛选下拉列表仅显示DEPT_ID=12的测试项?

要实现仅在Create视图的TEST_ID下拉列表中展示Dept_id=12的测试项,只需修改Create控制器方法中生成SelectList的逻辑,添加筛选条件即可,具体步骤如下:

修改Create控制器方法

当前你的Create方法直接传入了所有LabTests数据,我们需要添加Where子句筛选出Dept_id == 12的记录:

public ActionResult Create()
{
    // 仅筛选Dept_id为12的测试项
    var filteredTests = db.LabTests.Where(t => t.Dept_id == 12);
    ViewBag.TEST_ID = new SelectList(filteredTests, "TestId", "TestName");
    return View();
}

视图部分无需修改

你的.cshtml视图代码已经正确绑定了ViewBag.TEST_ID,保持现有代码即可:

<div class="form-group">
    @Html.LabelFor(model => model.TEST_ID, "TEST_ID", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("TEST_ID", null, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.TEST_ID, "", new { @class = "text-danger" })
    </div>
</div>

补充说明

  • 该逻辑会从LabTests表中仅获取部门ID为12的测试项,生成对应的下拉选项
  • 确保EF上下文db能正常访问LabTests表,且Dept_id字段类型与筛选值12匹配(此处为int类型,无需额外转换)

内容的提问来源于stack exchange,提问作者Ziad Adnan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 09:30:25