繁体   English   中英

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

[英]How to null check @Html.DisplayNameFor with IEnumerable - C# & ASP.NET MVC

我不确定是否搜索错误,但是我似乎无法确定如何对@Html.DisplayNameFor进行null检查。

我有一个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; }
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM