![](/img/trans.png)
[英]how to format a date time variable in asp.net mvc using @HTML.DisplayNameFor
[英]How to null check @Html.DisplayNameFor with IEnumerable - C# & ASP.NET MVC
我不確定是否搜索錯誤,但是我似乎無法確定如何對@Html.DisplayNameFor
進行null
檢查。
我有一個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
或.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.