c# - 如何使用 IEnumerable 对 @Html.DisplayNameFor 进行空检查 - C# & ASP.NET MVC
问题描述
我不确定我是否搜索不正确,但我似乎无法确定如何null
检查@Html.DisplayNameFor
.
我有一个IEnumerable<model>
其中有一个model.Numbers
model.Order
和model.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; }
}
解决方案
你@model
的是一个IEnumerable<T>
. 它没有.Numbers
or .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 帮助程序时,通常不需要处理空值。
推荐阅读
- php - 在模型中使用选择时模型返回空数组(Laravel)
- java - 当使用参数时,Testng 会忽略 @Test
- mysql - MySQL在字符串中定位第一个小写字母
- excel - How to get autofill formula to skip a row at a time and use correct formula?
- arrays - 根据 Google Sheet 中的某些变量创建水平列表
- ffmpeg - ffmpeg 错误:跳过的帧数过多 xxxxx > 60000
- call - 我可以使用 Microsoft Teams 在 Kiosk 桌面应用程序中进行语音/视频通话吗?
- python - 需要编写一个python函数来更改xml文件中的两个特定值
- c# - 在itextsharp中解析html时pdf中的行距
- c++ - 如何从包围体计算中排除空 QEntity