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
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.
Try the following:
<td>
@(item.Customer != null ? item.Customer.Name : "")
</td>
Edit: Enclosed to ensure it will work in Razor.