首页 > 解决方案 > 将 ID 分配给 ViewBag 并在 MVC 中为其赋值

问题描述

我目前有一个控制器,它循环通过我的“站点”数据库并根据他们的站点 ID 获取一个值它看起来像这样

 osiTotal[s.ID] = osiPartCost[s.ID] + osiCompCost[s.ID] + osiItemCost[s.ID];                 
 ViewBag.OSITotal[s.ID] = osiTotal[s.ID]; // Receive error message on this line

然后我的视图看起来像这样

 @foreach (Site s in sites)
{
 <tr>
                <td style="font-weight : bold;">Total</td>
                <td style="font-weight : bold;">@ViewBag.OSITotal[s.ID]</td>
 </tr>
}

但我收到错误

无法对空引用执行运行时绑定

我已经尝试按照我的观点这样做

 @foreach (Site s in sites)
{
 <tr>
                <td style="font-weight : bold;">Total</td>
                <td style="font-weight : bold;">@ViewBag.OSITotal[1]</td>
 </tr>
}

我自动分配@ViewBag.OSITotal“1”的值但仍然收到相同的错误

所以我的问题必须是当我试图将 osiTotal[s.ID] 的值分配给 ViewBag

为什么是这样?

标签: c#asp.net-mvclinqviewbag

解决方案


ViewBag.OSITotal 的类型是什么?您需要先创建并分配一个新数组或集合给它,否则它将为空。ViewBag.OSITotal[0] 尝试取消引用一个空集合,给出错误。例如,如果 ID 是 int:

ViewBag.OSITotal = new Dictionary<int,int>();

推荐阅读