c# - Razor 安全导航运算符(operator)?

标签 c# asp.net-mvc razor

是否有一种方法可以以空安全方式在 Razor View 中导航对象图(无需使用 @if 保护 block ?

例如,我在 Index.cshtml 中有以下内容:

@foreach (Store.Models.Product product in @Model)
{
    <tr>
        <td>@product.Id</td>  
        <td>@product.ProductName</td>  
        <td>@String.Format("{0:C}", @product.Price)</td>
        <td>@product.Quantity</td>
        @if (@product.Category != null)
        {
            <td>@product.Category.CategoryName</td>
        }
        else 
        {
            <td></td>
        }
    </tr>
}

并非我的所有产品都有类别。如果不这样做,Product.Category 为 null。

我真正想做的是能够安全地导航对象图,而不必担心 NullReferenceException 破坏 View 。

在 Groovy/Grails 中,我习惯使用 Safe Navigation Operator并会做类似的事情:

<td>@product?.Category?.CategoryName</td>

当然,这在 Razor 中行不通。

Razor 中有类似的东西吗?

最佳答案

一种方法是使用内联条件:

<td>@(product.Category != null ? product.Category : "")</td>

只是让代码更加紧凑

关于c# - Razor 安全导航运算符(operator)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15749216/

相关文章:

c# - 如何复制具有不同名称的工作表 - C# 和 Excel Interop

c# - 用不同的程序序列化c#

c# - 从 Request.Files 中删除文件

c# - 下拉列表 - MVC3

asp.net-mvc - ASP.NET MVC ActionLink 与 URL 重写

razor - HandleError 在带有 Razor 的 Asp.net MVC 4 中是否继续工作

c# - c#razor 字符串与带有尾部斜杠的 html 字符串的连接

c# - 旋转外部 N x N 方阵,同时保持内部方阵不变

c# - ASP.NET MVC 5、IIS Express 8 - 未达到索引

javascript - 具有特殊字符的数据库值,使用它们的 HTML 编号呈现,而不是使用数据库中的数据