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

ASP.NET Core MVC视图使用ViewModel中List<Model>时出现空引用异常

解决Asp.Net Core Razor视图中NullReferenceException问题

错误原因分析

报错Microsoft.AspNetCore.Mvc.Razor.RazorPage.Model.get返回null,核心原因是视图接收的CreatePostViewModel实例为null,或者其PostCategoryList属性未被初始化赋值,导致视图中直接访问Model.PostCategoryList时触发空引用异常。


具体解决方案

1. 修复控制器传递视图模型的逻辑

确保控制器在返回视图时,传递了已初始化并赋值的CreatePostViewModel实例,包括GET请求渲染页面和POST请求验证失败回显页面的场景:

// GET请求加载创建页面
public IActionResult Create()
{
    var viewModel = new CreatePostViewModel();
    // 从数据库查询分类数据并赋值
    viewModel.PostCategoryList = _dbContext.PostCategories.ToList();
    return View(viewModel); // 必须将viewModel传入View方法
}

// POST请求处理表单提交
[HttpPost]
public IActionResult Create(CreatePostViewModel model)
{
    if (!ModelState.IsValid)
    {
        // 验证失败时,重新加载分类数据(表单不会回传该列表)
        model.PostCategoryList = _dbContext.PostCategories.ToList();
        return View(model);
    }
    // 执行保存逻辑
    _dbContext.Posts.Add(new PostModel { /* 赋值属性 */ });
    _dbContext.SaveChanges();
    return RedirectToAction("Index");
}

2. 视图层增加空值防护判断

在视图中直接访问Model或其属性前,先做非空判断,避免空引用:

<div class="col-md-12 mb-3">
    <label asp-for="PostCategory" class="form-label">Post Category</label>
    <select asp-for="PostCategory" class="form-select" required>
        <option hidden selected>Open this select menu</option>
        @if (Model != null && Model.PostCategoryList != null)
        {
            foreach (var item in Model.PostCategoryList)
            {
                <option value="@item.Id">@item.CategoryName</option>
            }
        }
    </select>
    <div class="invalid-feedback">
        Please select a valid category.
    </div>
</div>

3. 优化ViewModel的属性初始化(可选)

在ViewModel的构造函数或属性声明时,直接初始化PostCategoryList为空列表,从根源避免属性为null:

public class CreatePostViewModel
{
    // 其他属性...

    // 初始化空列表,替代可空类型
    public List<PostCategoryModel> PostCategoryList { get; set; } = new List<PostCategoryModel>();
}

常见踩坑点

  • 控制器返回View()而非View(viewModel),导致视图的Model为null
  • POST请求验证失败返回视图时,未重新赋值PostCategoryList(表单提交不会携带该列表数据)
  • 视图未做空值判断,直接访问Model.PostCategoryList触发异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 20:22:17