在调试中已经显示数据时,将数据附加到运行时将引发null异常

时间:2019-05-09 01:30:25

标签: c# asp.net-mvc

将数据附加到表数据元素时,foreach文件中的cshtml引发空异常

我尝试调试

@foreach (onlineStore.Areas.Admin.Models.orderModel i in ViewBag.data)
{
       <tr>
           <td>@i.uName</td>
           <td>@i.oDate</td>
           <td>@i.tCost</td>  //throws exception here 
           <td>
           <a asp-action="Details" asp-controller="Admin" asp-area="Admin" asp-route-userid="@ViewBag.i.oID" class="btn btn-primary">Details</a>
           </td>
       </tr>
}

here is an image of the data at he debugging

例外是:

  

“ Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:'无法   在空引用上执行运行时绑定'“

1 个答案:

答案 0 :(得分:1)

使用前,您需要检查ViewBag.data != null

可能将错误的变量@ViewBag.i.oID更改为i.oID

@if (ViewBag.data != null)
{
     foreach (onlineStore.Areas.Admin.Models.orderModel i in ViewBag.data)
     {
         <tr>
             <td>@i.uName</td>
             <td>@i.oDate</td>
             <td>@i.tCost</td>  //throws exception here
             <td>
                 <a asp-action="Details" asp-controller="Admin" asp-area="Admin" asp-route-userid="@i.oID" class="btn btn-primary">Details</a>
             </td>
         </tr>
     }
}