如何处理在MVC剃刀空子实体 [英] How to handle null child Entities in MVC Razor

查看:108
本文介绍了如何处理在MVC剃刀空子实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MVC剃刀观点,即通过一个订单集合迭代。每个订单有一个客户,它可以为null。

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炸毁时item.Customer为空(如你所期望)。

@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 ?

谢谢
邓肯

推荐答案

一个简单的,如果应该做的工作:

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.

这篇关于如何处理在MVC剃刀空子实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆