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

ASP.NET Core MVC 3.1表单提交跨页展示数据报空引用错误如何解决

问题根因

  1. 表单提交按钮误用了<a>标签,点击后直接发起GET请求跳转,不会触发表单POST提交逻辑,表单数据完全没有传递到后端
  2. [HttpPost]修饰的Book动作接收到表单数据后没有做存储,也没有跳转到Review页面
  3. Review动作没有给视图传递任何模型数据,视图绑定的IEnumerable<Form>为null,遍历的时候触发空引用异常

解决步骤

步骤1:修改Book.cshtml的提交按钮

将原有超链接提交按钮替换为原生提交按钮,触发表单POST提交:

<!-- 替换原有代码 -->
<!-- <a type="submit" class="btn btn-dark" href="https://localhost:44348/Home/Review">Next</a> -->
<button type="submit" class="btn btn-dark">Next</button>

同时优化Book的GET动作,给视图传递空模型避免绑定时潜在空引用:

[HttpGet]
public IActionResult Book()
{
    return View(new Form());
}

步骤2:配置Session服务(ASP.NET Core 3.1)

我们用Session跨请求存储表单提交记录,首先修改Startup.cs文件:
在ConfigureServices方法中添加服务注册:

// 注册内存缓存,Session依赖该服务
services.AddDistributedMemoryCache();
services.AddSession(options => 
{
    options.IdleTimeout = TimeSpan.FromMinutes(30);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

在Configure方法中,UseRouting之后、UseAuthorization之前添加Session中间件:

app.UseSession();

步骤3:修改HomeController业务逻辑

先安装Newtonsoft.JsonNuget包用于序列化对象存储,然后修改控制器代码:

using Newtonsoft.Json;

[HttpPost]
public IActionResult Book(Form form)
{
    if(ModelState.IsValid)
    {
        // 读取Session中已存储的表单列表
        List<Form> formList = new List<Form>();
        var sessionData = HttpContext.Session.GetString("FormList");
        if (!string.IsNullOrEmpty(sessionData))
        {
            formList = JsonConvert.DeserializeObject<List<Form>>(sessionData);
        }
        // 新增当前提交的表单
        formList.Add(form);
        // 存回Session
        HttpContext.Session.SetString("FormList", JsonConvert.SerializeObject(formList));
        // 跳转到Review页面
        return RedirectToAction("Review");
    }
    // 验证失败返回当前页,保留用户输入
    return View(form);
}

public IActionResult Review()
{
    List<Form> formList = new List<Form>();
    var sessionData = HttpContext.Session.GetString("FormList");
    if (!string.IsNullOrEmpty(sessionData))
    {
        formList = JsonConvert.DeserializeObject<List<Form>>(sessionData);
    }
    // 将表单列表传递给视图
    return View(formList);
}

可选优化

如果你只需要展示当前提交的单个表单,不需要历史提交列表,可以将Review.cshtml的模型改为单个Form类型,用TempData传递数据即可,不需要配置Session。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:18:03