c# - 将 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
为什么是这样?
解决方案
ViewBag.OSITotal 的类型是什么?您需要先创建并分配一个新数组或集合给它,否则它将为空。ViewBag.OSITotal[0] 尝试取消引用一个空集合,给出错误。例如,如果 ID 是 int:
ViewBag.OSITotal = new Dictionary<int,int>();
推荐阅读
- r - 指向闪亮的 tabPanel 的外部超链接
- javascript - 如何将本地 javascript 对象与远程 json 数据库(例如 firebase)同步
- tesseract - tesseract 5 不会识别几个不费吹灰之力的个位数,任何指针都会非常受欢迎
- javascript - Firebase CORS XMLHttpRequest 已被阻止的问题
- ios - iOS React Native:添加除 Debug 和 Release 之外的构建配置
- c - 在 stm32f103c8t6 Blue Pill 中启用输出端口
- angular - nativescript-background-http 分离视图
- java - 数组元素点浮点数被截断
- python - Sklearn Pipeline 连接轴的所有输入数组维度必须完全匹配
- java - 无法让 RecyclerView 水平显示 Android Java