如何使用IEnumerable空检查@ Html.DisplayNameFor-C#和ASP.NET MVC

时间:2019-06-02 16:09:09

标签: 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; }
}

1 个答案:

答案 0 :(得分:2)

您的@modelIEnumerable<T>。它不包含其中包含的对象.Numbers.Order

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

所以

<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为空,或者.First()为空,或者整个Model为空,这也将起作用。

在将表达式树传递给ASP.NET MVC帮助器时,通常不需要处理null。