tcode
tcode

Reputation: 5105

Return String instead of DateTime if LINQ Query NULL

I am using JQuery Datatables with my MVC 5 application. I am implementing sorting on one of my datatables within my MVC Controller. One of the columns displays dates to the user, and I want them to be able to sort this column, which works fine.

//Get index of column to be sorted
var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);

Func<survey_status, DateTime> orderingFunctionDate;

orderingFunctionDate = (c => c.InitiatedDate == null ? default(DateTime) : c.InitiatedDate.Value);

The problem is, at the moment, if c.InitiatedDate is NULL, then I return the default date 01/01/0001, otherwise I return the actual date recorded in the Database.

I don't like that I am returning 01/01/0001 to the user, it isn't great usability and could confuse them. Instead, I'd like to return something like "No date available" if c.InitiatedDate is NULL.

The problem is I can't replace

orderingFunctionDate = (c => c.InitiatedDate == null ? default(DateTime) : c.InitiatedDate.Value);

with

orderingFunctionDate = (c => c.InitiatedDate == null ? "No date available" : c.InitiatedDate.Value);

because the Function Func<survey_status, DateTime> orderingFunctionDate is returning a DateTime, not string and in making this change I get an error no implicit conversion between string and DateTime.

Can anyone help me out with this?

Any help would be greatly appreciated.

Thanks.

Upvotes: 0

Views: 436

Answers (1)

DavidG
DavidG

Reputation: 118987

You should use a nullabel DateTime and return null instead of a default date. Change your function prototype to:

Func<survey_status, DateTime?> orderingFunctionDate;

And the content to:

orderingFunctionDate = (c => c.InitiatedDate);

Then I believe in jQuery DataTables you can specify a value to use when data is null.

Upvotes: 1

Related Questions