PoliDev
PoliDev

Reputation: 1458

showing error when value is null in mvc

I have Locations column in my site. In database there is separate tables for ,

  1. Country
  2. State
  3. city
  4. Region

These all table id's are stored into Locations table then Location Table Id is referred to CandidatepreferredLocation.

My problem is, i want to show what location candidates stored.

Eg:

Location: Country, state, city,Region like that.

In the above, if city is null means it shows "object reference not set to an object."

So I use code like following,

still showing same error. i don't know. Any one suggest me?

Upvotes: 2

Views: 101

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038840

. what is the mistake here

You didn't check whether the corresponding properties are not null before using them:

<% foreach (Dial4Jobz.Models.CandidatePreferredLocation cl in Model.CandidatePreferredLocations) { %>
    <% if (cl.Location != null) { %>
        <% if (cl.Location.Country != null) { %>
            <%: cl.Location.Country.Name %>
        <% } %>
        <% if (cl.Location.State != null) { %>
            <%: cl.Location.State.Name %>
        <% } %>
        <% if (cl.Location.City != null) { %>
            <%: cl.Location.City.Name %>
        <% } %>
        <% if (cl.Location.Region != null) { %>
            <%: cl.Location.Region.Name %>
        <% } %>
    <% } %>
<% } %>

Of course in order to avoid those checks in the view you could make sure that those properties are correctly initialized in your controller action that is serving this view.

Upvotes: 1

Related Questions