如何在MVC Razor中处理null子实体

Dun*_*can 8 asp.net entity-framework razor asp.net-mvc-3

我有一个MVC剃刀视图迭代Orders集合.每个订单都有一个Customer,可以为null.

麻烦的是,在这种情况下,我得到一个空引用异常.

@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>
Run Code Online (Sandbox Code Playgroud)

当item.Customer为null(正如您所期望的那样)时,@ item.Customer.Name会爆炸.

这一定是一个简单的问题,但一直无法找到答案!

在没有设置ViewModel的情况下,处理此问题的最佳方法是什么?

谢谢邓肯

Leo*_*ons 7

请尝试以下方法:

<td>        
    @(item.Customer != null ? item.Customer.Name : "")
</td>
Run Code Online (Sandbox Code Playgroud)

编辑:附上以确保它在Razor中有效.


Fre*_*ood 5

首先,Html.DisplayFor(m => m[i].Customer.Name)如果您使用迭代而不是foreach,则可以使用内置的html帮助器.但这有点缺点.您可能没有索引器集合属性和DisplayFor方法获取表达式参数并编译它是昂贵的.

而不是它们,您可以创建自己的方法来更好地处理这种情况,如下所示.

public static class Utility
{
    public static TValue NullSafe<T,TValue>(this T obj,Func<T,TValue> value)
    {
        try
        {
            return value(obj);
        }
        catch (NullReferenceException/*Exception can be better choice instead of NullReferenceException*/)
        {
            return default(TValue);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在你可以愉快地使用它了

@item.NullSafe(m=>m.Customer.Name)
Run Code Online (Sandbox Code Playgroud)

将NullSafe方法作为扩展或静态是您的选择.


Dar*_*rov 4

一个简单的 if 应该完成这项工作:

<td>
    @if (item.Customer != null)
    {
        <text>@item.Customer.Name</text>
    }
</td>
Run Code Online (Sandbox Code Playgroud)

话虽如此,这只是一种解决方法。真正的解决方案在于定义和使用特定的视图模型。