8
<b>Start Date: </b>@employee["StartDate"].<br />

使用 MVC Razor 3/C#,如何检查employee["StartDate"]cshtml 中的值是否为空/空?因此,如果是,我改为显示:

<b>Start Date: </b>Unknown.<br />

我试过了:

@if(employee["StartDate"] == null){<b>Start Date: </b>Unknown.<br />} 

但这不起作用。

4

5 回答 5

14

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.

于 2013-06-24T18:38:12.733 回答
5

If you are only worried about null or empty

@(String.IsNullOrEmpty(employee["StartDate"])?"Unknow":employee["StartDate"])
于 2013-06-24T18:39:34.853 回答
3

我最终使用了这个:

@if(employee["StartDate"].ToString() == ""){<b>Start Date: </b>Unknown.<br />}
else{<Start Date: </b>@employee["StartDate"].<br />}

但是有没有一种“更干净”的方式来写这个?

于 2013-06-24T18:42:41.127 回答
1

If startDate is a DateTime try to compare it with DateTime.MinValue.

If you have more problems you can put breakpoint in razor code to see what exactly is that field

于 2013-06-24T18:38:39.513 回答
-1

像下面这样尝试过,我已经厌倦了类似的空检查,它应该可以工作

@if(employee["StartDate"] != DateTime.MinValue){
  <Start Date: </b>@employee["StartDate"].<br />
}
else{
  <b>Start Date: </b>Unknown.<br />
}
于 2016-05-19T16:20:06.873 回答