【问题标题】:Assigning an ID to a ViewBag and giving it a value in MVC将 ID 分配给 ViewBag 并在 MVC 中为其赋值
【发布时间】:2020-03-17 21:09:49
【问题描述】:

我目前有一个控制器循环浏览我的“站点”数据库并根据其站点 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-mvc linq viewbag


    【解决方案1】:

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

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

    【讨论】:

    • 它的类型是float
    • 现在在我看来,我在 ViewBag 上收到错误消息“字典中不存在给定的键。”