zoukankan      html  css  js  c++  java
  • 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");

    妙。

  • 相关阅读:
    网页设计太麻烦?15款免费优质Bootstrap UI工具包助你效率倍增!
    【自古套路得人心】最全UI图表设计技巧和套路,分分钟打造最优设计
    原型对接工作流!摹客全面支持Axure原型
    赶紧收藏!41个Web UI工具包资源免费及付费下载
    2019年设计师必看,UI加载动画完全解读
    845G
    845G
    845D
    845C
    845B
  • 原文地址:https://www.cnblogs.com/keepee/p/11326750.html
Copyright © 2011-2022 走看看