Reputation: 465
<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:
<b>Start Date: </b>Unknown.<br />
I tried:
@if(employee["StartDate"] == null){<b>Start Date: </b>Unknown.<br />}
but that doesn't work.
Upvotes: 8
Views: 36349
Reputation: 1
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 />
}
Upvotes: -1
Reputation: 465
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?
Upvotes: 3
Reputation: 218702
If you are only worried about null or empty
@(String.IsNullOrEmpty(employee["StartDate"])?"Unknow":employee["StartDate"])
Upvotes: 6
Reputation: 19830
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
Upvotes: 1
Reputation: 152501
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
.
Upvotes: 16