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

ASP.NET 6 MVC+EF实现下拉列表仅显示活跃Incident的技术问询

解决ASP.NET 6 MVC中下拉列表仅显示活跃Incident的问题

在基于ASP.NET 6 MVC并通过Entity Framework连接SQL Server的项目中,创建Transaction对象时需通过下拉列表选择Incident建立关联。Incident类包含IsActive布尔属性,当前下拉列表可正常显示所有Incident,但需求是仅展示IsActive = true的活跃项。只需在Transaction控制器的Create方法中,通过EF的筛选语法过滤出活跃Incident即可。

修改GET请求的Create方法

原代码直接获取所有Incident,添加Where(i => i.IsActive)筛选条件即可只保留活跃项:

public TransactionController(MyAppDbContext context)
{
    _context = context;
}

public IActionResult Create()
{
    // 仅筛选IsActive为true的Incident生成下拉列表
    ViewBag.Incident = new SelectList(_context.Incidents.Where(i => i.IsActive).ToList(), "IncidentId", "IncidentName");
    return View();
}

修改POST请求的Create方法

当表单验证失败返回视图时,同样需要保证下拉列表只显示活跃项,因此Post方法里的ViewBag赋值也要同步修改:

// POST: Transactions/Create       
[HttpPost]
public async Task<IActionResult> Create([FromForm] Transaction transaction)
{
    ModelState.Remove("Incident.IncidentName");
    if (ModelState.IsValid)
    {
        transaction.Incident = _context.Incidents.Find(transaction.Incident.IncidentId);
        _context.Add(transaction);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    // 验证失败时同样只加载活跃Incident
    ViewBag.Incident = new SelectList(_context.Incidents.Where(i => i.IsActive).ToList(), "IncidentId", "IncidentName");
    return View(transaction);
}

视图代码无需修改

视图中的下拉列表代码保持原逻辑即可,因为它只是绑定ViewBag中的数据源:

<div class="form-group">
    <label asp-for="Incident.IncidentId" class="control-label"></label>
    <select asp-for="Incident.IncidentId" asp-items="@ViewBag.Incident" class="form-control">
        <option>Pick an incident</option>
    </select>
    <span asp-validation-for="Incident.IncidentId" class="text-danger"></span>
</div>

额外提示

如果项目规模较大,建议使用强类型视图模型替代ViewBag,这样能获得更好的类型检查和代码提示,减少潜在错误。比如创建一个TransactionCreateViewModel,包含SelectList类型的ActiveIncidents属性,再传递给视图。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:35:27