dan henderson
asked on
c# allow nulls or empty strings in json
I have created a controller for a KeyLog (users check in keys or check out keys) from a physical box. I return a list of log entries to a free fqGrid control via json. Below is my controller code:
The problem is that this code errors on the time vaues if one of them is null. How can I get around this? The date vaules are not a problem.
var jsonData = new
{
rows = from logs in db.KeyLogs.Where(k => k.KeyId == id).ToList()
select new
{
id = logs.Id,
keyId = logs.KeyId,
removeDate = logs.KeyRemovedDate.HasValue ? logs.KeyRemovedDate.Value.ToString("MM/dd/yyyy") : "",
removeTime = logs.TimeOut.HasValue ? logs.TimeOut.Value.ToString("HH:mm:ss") : "",
returnDate = logs.KeyReturnedDate.HasValue ? logs.KeyReturnedDate.Value.ToString("MM/dd/yyyy") : "",
returnTime = logs.TimeIn.HasValue ? logs.TimeIn.Value.ToString("HH:mm:ss") : " ",
officer = logs.Officer
}
};
The problem is that this code errors on the time vaues if one of them is null. How can I get around this? The date vaules are not a problem.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You might want to post the error you're getting. If your db values truly are null, then your code should work. If they're not (maybe empty strings) then the HasValue will return true and you then try to format an empty string to a time - probably giving you a FormatException, rather than a Null exception
ASKER
sorry for the delay in responding. this worked for me.