views:

476

answers:

2

I'm looking for a clean way to handle null object references in LINQ to SQL model class when they are passed to a View.

Simple example.

TableA has a FK into TableB. The FK relationship may or may not exist for any row in TableA.

My LINQ to SQL classes express this relationship as ClassA.ClassB.Property, but in some instances ClassA.ClassB is a null object due to the null foreign key

I want to list ClassA.Property and ClassA.ClassB.Property in a table in a view

So far my view code looks like

<td>
    <% if ((classA.classB) != null) { %>
        <%= Html.Encode(classA.classB.Property)%>
    <% } %>
</td>

Is there a cleaner way to do this in the View?

I've tried

<td>
    <%= Html.Encode(classA.classB.Property ?? "")%>
</td>

But that won't work as the null value is not "Property" but "classB".

I'm a newbie at the whole MVC thing, but the view seems like the right place to make the choice about how to handle the display of null values.

+4  A: 

<%= Html.Encode(classA.classB != null ? classA.classB.Property : "")%>

Alexander Taran
My forgotten friend the ternary operator.Thanks
Cephas
+2  A: 

Take the special formatting code and encapsulate it into a display helper class in your project to enable reuse and improve readability.

That Guy