简体   繁体   中英

How to use ToShortDateString() on nullable datetime column

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?)

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.

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 %>

Nullable DateTime should be formatted like below;

<%= Model.EndDate.HasValue ? 
     Model.EndDate.Value.ToShortDateString() : 
     "Something"%>

你可以试试下面,

<%= Model.EndDate != null ? Model.EndDate.ToShortDateString() : "n/a" %>

You can Try this.

<%= Model.EndDate!= DBNull.Value ? Model.EndDate.ToShortDateString() : string.empty %>

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM