C# 将ID分配给ViewBag并在MVC中为其赋值

C# 将ID分配给ViewBag并在MVC中为其赋值,c#,asp.net-mvc,linq,viewbag,C#,Asp.net Mvc,Linq,Viewbag,我目前有一个控制器,它在我的“站点”数据库中循环,并根据它们的站点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)

我目前有一个控制器,它在我的“站点”数据库中循环,并根据它们的站点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>
}
然后我的观点是这样的

 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(站点中的站点)
{
全部的
@ViewBag.OSITotal[s.ID]
}
但是我收到了错误

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

我试着这样做来改变我的观点

 @foreach (Site s in sites)
{
 <tr>
                <td style="font-weight : bold;">Total</td>
                <td style="font-weight : bold;">@ViewBag.OSITotal[1]</td>
 </tr>
}
@foreach(站点中的站点)
{
全部的
@ViewBag.OSITotal[1]
}
其中,我自动将
@ViewBag.OSITotal
的值指定为“1” 但仍然收到相同的错误

因此,当我试图将osiTotal[s.ID]的值分配给ViewBag时,问题就出现了


这是为什么?

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

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

它的类型现在在我的视图中是浮动的,我在ViewBag中收到一个错误,说“给定的键在字典中不存在。”