C# 在MVC中将值分配给ViewBag时,无法执行运行时绑定到空引用

C# 在MVC中将值分配给ViewBag时,无法执行运行时绑定到空引用,c#,html,asp.net-mvc,linq,C#,Html,Asp.net Mvc,Linq,我目前有一个控制器,它在我的站点数据库中循环,并根据它们的站点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 (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的基础是动态类型。你会得到 在运行时而不是编译时发生异常。所以你最好 当您加载母版页时,请检查是否有/HTTP值 您的请求中的值将与您需要的值相同

Title RuntimeBinderException是由正在处理的基础动态对象引起的 习惯于NET框架总是以某种方式抛出这些异常

例如:

在控制器中:

Dictionary<int, string> sites = new Dictionary<int, string> { {0, "zero" }, { 1, "one" }, { 2, "two" } };
var osiTotal = new string[3] { "Manual", "Semi", "Auto" };
string[] temp = new string[osiTotal.Length];
foreach (var s in sites)
    temp[s.Key] = osiTotal[s.Key];
ViewBag.SiteData = temp;
视图:


您的视图代码知道s.ID是什么吗?向我们展示声明此变量的视图代码。我在@JasenI中添加了它。我认为问题在于s.id。尝试调试并查看s.id是否包含int值。。。也许是空的,你在哪一行得到这个错误?@Sujay我在ViewBag.OSITotal[s.ID]=OSITotal[s.ID]上得到它;并且s.ID不是空的