首页 > 解决方案 > 如何使用 IEnumerable 对 @Html.DisplayNameFor 进行空检查 - C# & ASP.NET MVC

问题描述

我不确定我是否搜索不正确,但我似乎无法确定如何null检查@Html.DisplayNameFor.

我有一个IEnumerable<model>其中有一个model.Numbers model.Ordermodel.Time

@Html.DisplayNameFor(Model => Model.Numbers)

等等

我尝试这样做,但 VS 在以下位置引发错误:

@Html.DisplayNameFor(Model => Model?.Numbers)

但是当我将鼠标悬停在 VS 中的红色波浪上时,我收到了这条消息:

表达式树 lambda 可能不包含空传播运算符

我也尝试过追加where()@Html.DisplayNameFor(Model => Model.Numbers.Any())但这些不起作用。

我的代码:

@model IEnumerable<BusinessLayer.NumbersModel>

...

<table class="table table-sm">

    <thead class="thead-dark">
        <tr>
            <th>@Html.DisplayNameFor(Model => Model.Numbers)</th>
            <th>@Html.DisplayNameFor(Model => Model.Order)</th>
            <th>@Html.DisplayNameFor(Model => Model.Time)</th>
        </tr>
    </thead>

    @foreach (var item in Model)
    {
        if (item.Numbers != null && item.Order != null && item.Time != null)
        {
            <tr>
                <td>@Html.DisplayFor(m => item.Numbers)</td>
                <td>@Html.DisplayFor(m => item.Order)</td>
                <td>@Html.DisplayFor(m => item.Time)</td>
                <td><i class="m-icon--edit"></i> @Html.ActionLink("Edit", "Edit", new { id = item.ID }, new { @class = "m-numbers__link" })</td>
                <td>
                    @using (Html.BeginForm("Delete", "Numbers", new { id = item.ID }))
                    {
                        <i class="m-icon--delete"></i> <input type="submit" value="Bin" onclick="return confirm('You are about to delete this record');" />
                    }
                </td>
            </tr>
        }
    }
</table>

模型:

public class NumbersModel
{
    public int ID { get; set; }
    public string Numbers { get; set; }
    public string Order { get; set; }
    public string Time { get; set; }
}

标签: c#asp.net-mvc

解决方案


@model的是一个IEnumerable<T>. 它没有.Numbersor .Order,它包含的对象有。

DisplayNameFor()只需要知道表达式的类型即可从中获取属性DisplayAttribute。您传递给它的表达式不必计算到对象的非空实例,它不会为其结果执行。

所以

<thead class="thead-dark">
    <tr>
        <th>@Html.DisplayNameFor(m => m.First().Numbers)</th>
        <th>@Html.DisplayNameFor(m => m.First().Order)</th>
        <th>@Html.DisplayNameFor(m => m.First().Time)</th>
    </tr>
</thead>

即使.Numbers为 null、或.First()为 null 或整个Model为 null,这也将起作用。

将表达式树传递给 ASP.NET MVC 帮助程序时,通常不需要处理空值。


推荐阅读