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

从SQLite删数据后重定向至Index页出现NullReferenceException

问题解决:删除后重定向Index页出现NullReferenceException

问题根源

你的DeleteConfirmed方法直接返回Index视图,但没有传入视图所需的模型数据。手动访问Index页时,会调用Index action方法,该方法会从数据库获取最新分类列表并传入视图,所以正常显示;但删除后直接返回视图时,视图没有收到模型数据,导致Model为null,触发@foreach (var item in Model!)的空引用异常。

解决方案

不要直接返回Index视图,而是使用RedirectToAction跳转到Index action方法,让它执行获取数据的逻辑并返回带模型的视图。

修改DeleteConfirmed方法:

// POST: Categories/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
    await _logic.RemoveCategoryFromProducts(id);
    await _logic.RemoveCategory(id);
    // 替换原return View("Index")为以下代码
    return RedirectToAction(nameof(Index));
}

原理说明

  • return View("Index"):仅渲染指定视图,不会触发对应action方法的执行,因此没有模型数据传入视图。
  • RedirectToAction(nameof(Index)):发起一个新的GET请求到Index action方法,该方法会重新从数据库获取最新的分类列表,再将模型传入视图,确保视图有可用数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 20:20:27