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

Razor Pages中foreach语句用法及Case模型空引用错误排查求助

解决Edit.cshtml中foreach构建Species下拉框的空引用问题

核心问题分析

你遇到的空引用错误,大概率是两个原因:

  1. Edit页面的后台Get方法没有像Create页面那样传递Species集合到前台,导致foreach遍历null时抛出异常
  2. 目标Case模型本身为空(比如未找到对应ID的记录),导致访问Model.SpecieId时出错

正确的foreach下拉框写法(前台)

直接可用的前台代码,同时加入空值判断避免异常:

<select asp-for="SpecieId" class="form-control">
    <!-- 默认占位选项 -->
    <option value="">-- 选择物种 --</option>
    <!-- 先判断Species集合是否存在,再遍历 -->
    @if (ViewBag.Species != null)
    {
        foreach (var species in ViewBag.Species)
        {
            <!-- 匹配当前Case的SpecieId,自动选中对应选项 -->
            <option value="@species.SpecieId" @(Model.SpecieId == species.SpecieId ? "selected" : "")>
                @species.SpeciesName
            </option>
        }
    }
</select>

后台代码修正(关键)

在Controller的Edit Get方法中,必须和Create页面一样传递Species集合到前台,同时确保Case模型不为空:

public IActionResult Edit(int id)
{
    // 获取目标Case记录
    var caseModel = _context.Cases.Find(id);
    if (caseModel == null)
    {
        return NotFound(); // 记录不存在时返回404,避免后续空引用
    }
    // 和Create页面逻辑一致,传递Species列表到ViewBag
    ViewBag.Species = _context.Species.ToList();
    return View(caseModel);
}

进阶:使用ViewModel优化(更稳健)

如果不想依赖ViewBag,可以封装ViewModel传递数据,减少空引用风险:

  1. 创建ViewModel类:
public class CaseEditViewModel
{
    public Case Case { get; set; }
    public List<Species> SpeciesList { get; set; }
}
  1. 修改后台Edit方法:
public IActionResult Edit(int id)
{
    var caseModel = _context.Cases.Find(id);
    if (caseModel == null)
    {
        return NotFound();
    }
    var viewModel = new CaseEditViewModel
    {
        Case = caseModel,
        SpeciesList = _context.Species.ToList()
    };
    return View(viewModel);
}
  1. 前台修改模型引用并调整下拉框代码:
@model RabiesShotTracker.Models.CaseEditViewModel

<select asp-for="Case.SpecieId" class="form-control">
    <option value="">-- 选择物种 --</option>
    @if (Model.SpeciesList != null)
    {
        foreach (var species in Model.SpeciesList)
        {
            <option value="@species.SpecieId" @(Model.Case.SpecieId == species.SpecieId ? "selected" : "")>
                @species.SpeciesName
            </option>
        }
    }
</select>

验证要点

  • 确认后台Edit方法中_context.Species.ToList()能正常返回数据(和Create页面一致)
  • 确认传入的ID存在对应Case记录,避免Model为空
  • 前台必须先判断集合是否为null,再执行foreach遍历

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 07:53:29