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 iterates over an Orders collection. Each order has a Customer, which can be null.

Trouble is, I get a null reference exception when this is the case.

@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.Name blows up when item.Customer is null (as you'd expect).

This must be an easy question but haven't been able to find the answer!

What's the best way to deal with this, without setting up a ViewModel ?

Thanks Duncan

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

Accepted Answer

A simple if should do the job:

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

This being said and shown, that's only a workaround. The real solution consists in defining and using a specific view model.

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

Popular Answer

Try the following:

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

Edit: Enclosed to ensure it will work in Razor.



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