C# 如何检查 cshtml 中的空/空值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17282554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I check for null/empty value in cshtml
提问by sharcfinz
<b>Start Date: </b>@employee["StartDate"].<br />
Using MVC Razor 3/C#, how can I check if employee["StartDate"]value is null/empty in the cshtml? So that if it is, I instead display:
使用 MVC Razor 3/C#,如何检查employee["StartDate"]cshtml 中的值是否为空/空?因此,如果是这样,我会改为显示:
<b>Start Date: </b>Unknown.<br />
I tried:
我试过:
@if(employee["StartDate"] == null){<b>Start Date: </b>Unknown.<br />}
but that doesn't work.
但这不起作用。
回答by D Stanley
Try
尝试
<b>Start Date: </b>@(employee["StartDate"] ?? "Unknown").<br />
??return the left-side value, or the right-side value if the left-side value is null.
??返回左侧值,如果左侧值为 ,则返回右侧值null。
回答by Piotr Stapp
If startDate is a DateTimetry to compare it with DateTime.MinValue.
如果 startDate 是DateTime尝试将其与DateTime.MinValue.
If you have more problems you can put breakpoint in razor code to see what exactly is that field
如果您有更多问题,您可以在 razor 代码中放置断点以查看该字段到底是什么
回答by Shyju
If you are only worried about null or empty
如果您只担心 null 或 empty
@(String.IsNullOrEmpty(employee["StartDate"])?"Unknow":employee["StartDate"])
回答by sharcfinz
I ended up using this:
我最终使用了这个:
@if(employee["StartDate"].ToString() == ""){<b>Start Date: </b>Unknown.<br />}
else{<Start Date: </b>@employee["StartDate"].<br />}
But is there a "cleaner" way to write this?
但是有没有一种“更干净”的方式来写这个?
回答by Azkar Khan
Have tried like below, I have tired similar null check, it should work
尝试过如下,我厌倦了类似的空检查,它应该可以工作
@if(employee["StartDate"] != DateTime.MinValue){
<Start Date: </b>@employee["StartDate"].<br />
}
else{
<b>Start Date: </b>Unknown.<br />
}

