Asp.net mvc 2 显示错误的空引用对象

Asp.net mvc 2 显示错误的空引用对象,asp.net-mvc-2,null,zero,Asp.net Mvc 2,Null,Zero,我在候选者表中有位置ID。我想在“详细信息”页面中显示这个。如果Locationid为空,则表示db存储了0值。否则,id值就在那里 当我尝试在详细信息页面中显示时,每当id有0值显示以下错误时,即使我也检查空条件 **"object reference not set to an object"** 我的密码是 <%if (Model.LocationId != null) { %> <% if (Model.GetLocation

我在候选者表中有位置ID。我想在“详细信息”页面中显示这个。如果Locationid为空,则表示db存储了0值。否则,id值就在那里

当我尝试在详细信息页面中显示时,每当id有0值显示以下错误时,即使我也检查空条件

      **"object reference not set to an object"**
我的密码是

 <%if (Model.LocationId != null)
      { %>
        <% if (Model.GetLocation(Model.LocationId.Value).CityId != null)
           {%>
               <%:Model.GetLocation(Model.LocationId.Value).City.Name%><%:","%>
        <% } %>
        <% if (Model.GetLocation(Model.LocationId.Value).CountryId != null)
           {%>
               <%:Model.GetLocation(Model.LocationId.Value).Country.Name%>
        <% } %>
        <% } %>
 <%if (Model.LocationId != 0)
      { %>
        <% if (Model.GetLocation(Model.LocationId.Value).CityId != null)
           {%>
               <%:Model.GetLocation(Model.LocationId.Value).City.Name%><%:","%>
        <% } %>
        <% if (Model.GetLocation(Model.LocationId.Value).CountryId != null)
           {%>
               <%:Model.GetLocation(Model.LocationId.Value).Country.Name%>
        <% } %>
        <% } %>


请将此设置为不显示错误

我发现了问题。我检查而不是
locationId=空
位置ID=0

我的密码是

 <%if (Model.LocationId != null)
      { %>
        <% if (Model.GetLocation(Model.LocationId.Value).CityId != null)
           {%>
               <%:Model.GetLocation(Model.LocationId.Value).City.Name%><%:","%>
        <% } %>
        <% if (Model.GetLocation(Model.LocationId.Value).CountryId != null)
           {%>
               <%:Model.GetLocation(Model.LocationId.Value).Country.Name%>
        <% } %>
        <% } %>
 <%if (Model.LocationId != 0)
      { %>
        <% if (Model.GetLocation(Model.LocationId.Value).CityId != null)
           {%>
               <%:Model.GetLocation(Model.LocationId.Value).City.Name%><%:","%>
        <% } %>
        <% if (Model.GetLocation(Model.LocationId.Value).CountryId != null)
           {%>
               <%:Model.GetLocation(Model.LocationId.Value).Country.Name%>
        <% } %>
        <% } %>


您可以在视图和调试中放置断点。我将。如果0表示它显示错误,那么只有我才能找到问题。我不知道零意味着如何设置条件?然后GetLocation()返回null City或Country。实际上Locationid存储所有位置。此Locationid来自Locations表。只需在GetLocation方法中放置一个断点。当id为0时,您可能会看到城市和国家属性为null。如果LocationId为null,您仍然会得到NullReferenceException。LocationId不为null。如果为null,则表示它在db中存储0。这就是我写的代码。