Reputation: 4620
How can I use ToShortDateString()
method when a datetime column allow nulls?
I get the following error on this asp.net code <%= Model.EndDate.ToShortDateString() %>
:
'System.Nullable' does not contain a definition for 'ToShortDateString' and no extension method 'ToShortDateString' accepting a first argument of type 'System.Nullable' could be found (are you missing a using directive or an assembly reference?)
Upvotes: 2
Views: 8199
Reputation: 4261
In С# 6 you can write the follows:
<%= Model.EndDate?.ToShortDateString() %>
In earlier versions it is common to write it as
<%= Model.EndDate != null ? Model.EndDate.Value.ToShortDateString() : null %>
Upvotes: 4
Reputation: 69
You can Try this.
<%= Model.EndDate!= DBNull.Value ? Model.EndDate.ToShortDateString() : string.empty %>
Thanks
Upvotes: 0
Reputation: 1898
Can you please try below,
<%= Model.EndDate != null ? Model.EndDate.ToShortDateString() : "n/a" %>
Upvotes: 0
Reputation: 3131
Nullable DateTime
should be formatted like below;
<%= Model.EndDate.HasValue ?
Model.EndDate.Value.ToShortDateString() :
"Something"%>
Upvotes: 0
Reputation: 2108
The corret way to do that is like in this example:
<%=Model.EndDate.HasValue ? Model.EndDate.Value.ToShortDateString() : string.Empty; %>
Nullable values always expose a property called "Value" that will contain data if is not null and another property, called "HasValue" that indicate if data is present or not.
Upvotes: 10