有一句代碼:
@Html.DisplayFor(modelItem => item.SellDate, "RegularDate")
RegularDate.cshtml?內容如下:
@model System.DateTime @Model.ToString("yyyy/MM/dd")
目的是將數據庫里的?DateTime?顯示為完整日期,如 2019/08/09,時間部份舍去。
當?SellDate?不為空值時,用?"RegularDate"? 這個 templateName?來 render SellDate?很方便,特別是批量應用該 templateName的情況下。
?
但是數據庫里“SellDate”有可能為空,這樣會出一個錯誤:
The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.DateTime'.
說明: 執行當前 Web 請求期間,出現未經處理的異常。請檢查堆棧跟蹤信息,以了解有關該錯誤以及代碼中導致錯誤的出處的詳細信息。 異常詳細信息: System.InvalidOperationException: The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.DateTime'.源錯誤: 行 86: <td>
行 87: @**@
行 88: @Html.DisplayFor(modelItem => item.SellDate, "MyDate")
行 89: </td>
行 90: <td>源文件: D:\****\Index.cshtml 行: 88 這
這樣就有點不適合了,其實有另外一種更簡便的方法:
采用 ?.?操作符,這是一個 C#?語法糖:
@(item.SellDate?.ToString("yyyy/MM/dd"))
當 item.SellDate?不為空時就執行 .ToString("yyyy/MM/dd")。
相當于
if (!item.SellDate != null)item.SellDate.ToString("yyyy/MM/dd");
妙。