繁体   English   中英

为 ViewBag 分配 ID 并在 MVC 中为其赋值

[英]Assigning an ID to a ViewBag and giving it a value in 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 时

为什么是这样?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM