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

ASP.NET MVC视图访问ViewBag.cart的Custom属性报RuntimeBinderException错误

问题原因

你代码里的ViewBag.cart存储的是List<Item>类型的购物车集合,不是单个Item对象。你在视图里把整个集合赋值给dataCart之后,直接调用@dataCart.Custom.CustomerId,相当于试图给List类型调用不存在的Custom属性,自然会抛出运行时绑定异常。
之前循环遍历ViewBag.cart里的每个item能正常访问属性,也验证了单个Item对象的属性是正常的,就是因为你循环的时候取的是集合里的单个元素。

修复方案

根据你的业务场景选对应改法即可:

场景1:同一个购物车里所有Item的Customer都是同一个(常规购物车场景)

先判断集合非空再取第一个元素的属性即可,避免空引用报错:

@{
    var dataCart = ViewBag.cart as List<JAXSurplusMouseApp.Models.Item>;
    var customerId = dataCart?.FirstOrDefault()?.Custom?.CustomerId;
}
<!-- 按钮绑定正确的customerId -->
<a asp-action="Index" asp-controller="Inventories" asp-route-id="@customerId">Select</a>

场景2:每个Item对应不同的Customer需要单独传值

把这个a标签放到foreach循环内部,和每个Item一一对应即可:

@foreach (var item in ViewBag.cart)
{
    <tr>
        <td>@item.Inventory.StrainId</td>
        <td>@item.Inventory.StrainName</td>
        <td>@item.Quantity</td>
        <td><a asp-action="Index" asp-controller="Inventories" asp-route-id="@item.Custom.CustomerId">Select</a></td>
    </tr>
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:54:05