asp.net-mvc - 处理 "object reference not set to an instance of an object"错误

标签 asp.net-mvc entity-framework .net-4.0

我收到错误:

System.NullReferenceException occurred HResult=-2147467261 Message=Object reference not set to an instance of an object when attempting to access a view.

错误指向这一行:

<span>@(d.AcceptPropagation == null ? string.Empty : "Accepts Propagation")</span> 

我在 foreach 循环中设置了一个断点,并逐步查找发生 null 的位置。直到第五次循环时我才收到错误,并且在 DocumentTemplate 中得到 null。我认为我正确地处理了空值。我需要额外的空检查吗?我需要以不同的方式处理这个问题吗?下面是 View 。我还在代码中将“”更改为string.Empty。

@if (criteria != null)
        {
            foreach (var d in criteria)
            {
                <tr>
                    <td style="width: 80px;">
                        <a class="blue button edit-template" data-reveal-id="edit-form" id="@d.ID">Edit</a>
                    </td>
                    <td>
                        <strong>@(d.DocumentTemplate == null ? string.Empty: d.DocumentTemplate.Name)</strong><br />
                        <div>@d.GroupCode</div>
                        <span>@d.PlanCode</span>
                        <span>@d.SubPlanCode</span>
                        <span>@d.ActionCode</span>
                        <span>@d.AdmitTerm</span>
                        <span>@d.AdmitTypeCode</span>
                        <span>@d.ProgramCode</span>
                        <span>@d.ResidentCode</span>
                        <span>@(d.V19 == true ? "V19" : string.Empty)</span>
                        <span>@(d.A23 == true ? "A23" : string.Empty)</span>
                        <span>@(d.AcceptPropagation == null ? string.Empty : "Accepts Propagation")</span> 
                        <div><a href="@Url.Content(d.DocumentTemplate.Path)">@(Url.Content(d.DocumentTemplate.Path)==null? string.Empty : d.DocumentTemplate.Path)</a></div>
                    </td>
                </tr>
            }
        }

最佳答案

实际上是您提到的那一行下面的一行导致了问题。 Razor View NullReferenceExceptions 由于某种原因多次指向上面的行。将其下面的行更改为具有相同的空检查,它将起作用:

<div>
    @if(d.DocumentTemplate != null)
    {
        <a href="@Url.Content(d.DocumentTemplate.Path)">@d.DocumentTemplate.Path</a>    
    }
</div>

参见,this link用户最初发现问题的位置。

关于asp.net-mvc - 处理 "object reference not set to an instance of an object"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31277061/

相关文章:

c# - 如何知道哪个表阻止我使用 Entity Framework 6 删除行?

mysql - 使用 Entity Framework 6 和 MySql 的 DbUpdateConcurrencyException

c# - Xml Serializer 中的注释问题

javascript - AngularJS 缓存 $http.post 响应

jquery - 如何将 Html.Action 附加到 jquery

php - Doctrine 一对多关系 - "No identifier/primary key specified"

asp.net-mvc - 无法加载类型 'System.Web.Mvc.ViewMasterPage<dynamic>' .?

asp.net - 在 MVC2 中向用户传递消息

asp.net-mvc - Razor 中的 ViewBag.Title 是什么?

c# - foreach + break vs linq FirstOrDefault 性能差异