Reputation: 46222
I am trying to display the following in a view but is giving a problem:
<td>
@item.CreatedByDt.ToString("MM/dd/yyyy")
</td>
Any idea on how to handle a nullable Date field in a view. I am using Razor by the way.
I am getting the following error:
No overload for method 'ToString' takes 1 arguments
Upvotes: 22
Views: 17184
Reputation: 5122
If DateTime?
is a null value, they give an error.
This solution will not generate an error:
@functions{
string FormatNullableDate(DateTime? value) => value.HasValue ? value.Value.ToString("MM/dd/yyyy") : "-";
}
<td>
@FormatNullableDateTime(item.CreatedByDt)
</td>
Upvotes: 0
Reputation: 121
@(item.CreatedByDt.HasValue ? item.CreatedByDt.Value.ToString("MM/dd/yyyy") : "--/--/----")
You can replace the display string for when your date is null with what you want.
Upvotes: 12
Reputation: 26940
If you don't know if it will be null or not...
@string.Format("{0:MM/dd/yyyy}", item.CreatedByDt)
Upvotes: 36
Reputation: 2120
@item.PostDatePublished.Value.ToString
need the value in there
Upvotes: -2