C# ?. 判斷Null值

有一句代碼:

@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");

妙。

转载于:https://www.cnblogs.com/keepee/p/11326750.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值