[英]ASP.NET Razor Entity Framework Null reference exception
Here is the code that is causing the problem, it is inside the view: 这是导致问题的代码,它在视图内部:
@{
if(item.Contract_Type != null)
{
dangerhtml = (item.Contract_Type == "Premium") ? "class=\"warning\"" : "";
}
}
<td @dangerhtml>
@Html.DisplayFor(modelItem => item.Contract_Type)
</td>
This code is sitting inside a foreach: 这段代码位于foreach内部:
@foreach (var item in Model) {
..etc
}
It is throwing a NullReferenceException on the if line. 它在if行上抛出NullReferenceException。 The code works fine if I remove all the above and just do:
如果我删除以上所有内容并执行以下操作,则代码可以正常工作:
<td>
@Html.DisplayFor(modelItem => item.Contract_Type)
</td>
But I am looking to set the class for the cell based on the contents of the item.Contract_Type 但是我正在基于项目的内容设置单元格的类。
Any help appreciated! 任何帮助表示赞赏!
I'm pretty sure that item is null, as Luke has already mentioned and that @Html.DisplayFor will just swallow this. 我很确定该项目为null,就像Luke已经提到的那样,并且@ Html.DisplayFor会吞下这个。
Why don't you just add following where clause to prevent null-items from being processed: 为什么不添加以下where子句以防止空项目被处理:
@foreach (var item in Model.Where(i => i != null))
{
..etc
}
Or you can null-check the item before checking the Contract_Type to prevent the NullReferenceException from occurring: 或者,您可以在检查Contract_Type之前对项目进行空检查,以防止NullReferenceException发生:
if(item != null && item.Contract_Type != null)
{
dangerhtml = (item.Contract_Type == "Premium") ? "class=\"warning\"" : "";
}
But maybe the best approach would be to ensure that no null-object is written to the Model-collection before passing it to the view.. 但是,也许最好的方法是确保在将null对象传递给视图之前,不将任何空对象写入Model-collection。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.