In MVC Razor, how do you handle null child Entities?

asp.net asp.net-mvc-3 entity-framework razor

Question

I have an MVC razor view that loops over a collection of orders. Every order has a Customer, who may or may not exist.

The problem is that when this happens, I get a null reference error.

@foreach (var item in Model) {
<tr>
        <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.ID })
    </td>
    <td>
        @item.Number
    </td>
    <td>
        @String.Format("{0:g}", item.ReceivedDate)
    </td>
    <td>
        @item.Customer.Name
    </td>

@item.Customer. When object, the name explodes. Customer is null, as you could anticipate.

I know the solution to this question must be simple, but I can't seem to locate it!

Without creating a ViewModel, what is the best approach to handle this?

Thanks Duncan

1
8
4/26/2011 5:56:04 PM

Accepted Answer

An easy if should do the trick:

<td>
    @if (item.Customer != null)
    {
        <text>@item.Customer.Name</text>
    }
</td>

That's just a workaround, as has been stated and shown. The true answer is to define and apply a certain view model.

4
4/26/2011 6:00:02 PM

Popular Answer

Try these things:

<td>        
    @(item.Customer != null ? item.Customer.Name : "")
</td>

To make sure it will function in Razor, edit: enclosed.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow