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

ASP.NET Core MVC Linq结果传ViewData至PartialView报空引用异常

问题排查结果

空引用异常由以下几个代码问题共同导致:

  • ViewData键名完全不匹配:控制器向ViewData写入数据时用的键是ContractList,视图中先后尝试读取不存在的EmployeesList、contracts两个键,读取结果均为null,直接遍历null对象时就会抛出空引用异常。
  • EF Core查询逻辑错误:调用ToListAsync()方法时未添加await关键字,也没有将异步执行返回的结果赋值给变量,最终存入ViewData的是未执行的数据库查询对象(IQueryable),而非实际查询到的订单数据列表。
  • 异常处理逻辑缺陷:catch块直接返回null,既没有输出有效错误信息方便排查,还会导致视图渲染时因为接收到null的分部视图结果触发额外异常。
  • 视图代码冗余:声明了强类型@model但完全没有使用,还额外添加了<html>、<body>这类只应该出现在整页中的标签,会生成不符合规范的HTML结构。
修正后代码

1. HomeController中Backlog方法修正

// 异步方法需要添加async关键字,返回值改为Task<PartialViewResult>
public async Task<PartialViewResult> Backlog()
{
    try 
    { 
        // 加await等待异步查询执行完成,拿到实体列表
        var orderList = await FactoryContext.MoldingOrders.ToListAsync();
        // 直接将列表作为模型传给分部视图,避免ViewData键名不匹配问题
        return PartialView("~/Views/Shared/_Backlog.cshtml", orderList);
    }
    catch(Exception ex)
    {
        // 开发阶段可临时记录错误,返回空列表避免空引用
        return PartialView("~/Views/Shared/_Backlog.cshtml", new List<MoldingOrders>());
    }
}

2. _Backlog.cshtml局部视图修正

@using ProductionPlanningApp.Models;
@model IEnumerable<MoldingOrders>

<div class="overflow-auto position-absolute position-table">
    <table class="table table-bordered w-auto">
        <thead class="table-dark">
            <tr>
                <th class="text-md-center">BACKLOG</th>
            </tr>
        </thead>
        <tbody>
            @* 遍历强类型Model,加空值合并兜底避免空引用 *@
            @foreach(var item in Model ?? Enumerable.Empty<MoldingOrders>())
            {
                <tr class="d-flex">
                    <td>
                        <button type="button" class="btn btn-outline-dark btn-link btn-sm">@item.Auftrag</button>
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>

补充说明:如果偏好使用ViewData传值,必须保证控制器写入和视图读取的键名完全一致,不要随意修改键名拼写。分部视图只需要保留自身需要渲染的片段内容即可,不需要嵌套html、body这类顶层页面标签。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 05:31:00