首页 > 解决方案 > 在 MVC 中为 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)
{
 <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#htmlasp.net-mvclinq

解决方案


调用此类异常的原因:

ViewBag 的基础是动态类型。而且您将在运行时而不是在编译时获得异常。因此,您最好在 MasterPage - 页面加载时检查您的请求中是否包含与您需要的值相同的值/HTTP 值。看到这个链接

或者

Viewbag.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;

看法:

@{
    Dictionary<int, string> sites = new Dictionary<int, string> { { 0, "zero" }, { 1, "one" }, { 2, "two" } };
}
@foreach (var s in sites)
{
    <p>@ViewBag.SiteData[s.Key]</p>
}

推荐阅读