【问题标题】:How to null check @Html.DisplayNameFor with IEnumerable - C# & ASP.NET MVC如何使用 IEnumerable 对 @Html.DisplayNameFor 进行空检查 - C# & ASP.NET MVC
【发布时间】:2019-10-18 09:07:55
【问题描述】:

我不确定我是否搜索错误,但我似乎无法确定如何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; }
}

【问题讨论】:

  • 你遇到了什么错误?
  • An expression tree lambda may not contain a null propagating operator. 是当我用? 将鼠标悬停在VS 中的红色波浪线上时得到的
  • 你可能想阅读这个question接受的答案
  • 如果你的@modelIEnumerable&lt;model&gt;,那么你肯定不能打电话给.Numbers 等等。您可能在页面上有一个循环枚举Model,它是您传递给 lambda 的循环变量。
  • 我在调用DisplayNameFor 3 次后有一个循环,它遍历模型并通过DisplayFor 呈现数据

标签: c# asp.net-mvc


【解决方案1】:

您的@modelIEnumerable&lt;T&gt;。它没有.Numbers.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 为空,或.First() 为空,或整个Model 为空,这也将起作用。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    相关资源
    最近更新 更多