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

.NET Core 6 如何在View中显示Controller传递的求和值

ASP.NET Core MVC 视图展示关联表求和值实现方案

你当前代码的核心问题是Linq查询里直接用+拼接物料字段和求和结果,最终返回的是字符串集合,视图无法拆分读取单独的物料属性和结余数量值,按以下步骤调整即可:

1. 修正Controller查询逻辑

首先定义强类型视图模型,用来承载结构化的物料和结余数据,避免返回拼接的无结构字符串:

// 可以放在项目的Models目录下
public class ItemBalanceVm
{
    public string ItemCode { get; set; }
    public string ItemDesc { get; set; }
    public string Uom { get; set; }
    public string ItemReg { get; set; }
    // 数值类型请和你数据库中BalanceQty的实际类型匹配,例如decimal/int
    public decimal BalanceQty { get; set; }
}

调整Controller中的查询代码,投影为强类型集合:

public async Task<IActionResult> ItemBalanceList()
{
    var query = _context.ItemMaster
        .Select(x => new ItemBalanceVm
        {
            ItemCode = x.ItemCode,
            ItemDesc = x.ItemDesc,
            Uom = x.Uom,
            ItemReg = x.ItemReg,
            // 处理无关联交易记录的场景,避免空引用报错,无交易时结余返回0
            BalanceQty = x.Transaction.Sum(t => (decimal?)t.BalanceQty) ?? 0
        });
    return View(await query.ToListAsync());
}

如果只需要展示单个物料的结余,把ToListAsync()换成FirstOrDefaultAsync(x => x.ItemCode == 对应物料编码)即可,传递单个实体给视图。

2. 视图层渲染数据

在对应视图文件最顶部添加强类型模型声明,之后就可以直接读取模型里的字段,包括求和得到的BalanceQty:

@model List<ItemBalanceVm>

<h3>物料结余列表</h3>
<table class="table table-bordered">
    <thead>
        <tr>
            <th>物料编码</th>
            <th>物料名称</th>
            <th>计量单位</th>
            <th>登记信息</th>
            <th>结余数量</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.ItemCode</td>
                <td>@item.ItemDesc</td>
                <td>@item.Uom</td>
                <td>@item.ItemReg</td>
                <td>@item.BalanceQty</td>
            </tr>
        }
    </tbody>
</table>

如果是单物料视图,模型声明改为@model ItemBalanceVm,直接用@Model.BalanceQty即可在页面任意位置输出结余数量。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 17:57:20