Home > Enterprise >  Validation for null value of datetime
Validation for null value of datetime

Time:12-09

I would like to make an if else statement in my view file. if the date is not null, it will show the edited date. if its null then it will show Unavailable. But the datetime value will never be null as when I try to debug, it will show the default value 1/1/0001 12:00:00

grid.Column("edited_on", "Edited On", format: (item) =>
{
    if (item.edited_on.ToString() != "")
    {
        return Html.Raw(string.Format("{0:dd-MMM-yyyy}", item.edited_on));
    }
    else
    {
        return Html.Raw(string.Format("Unavailable"));
    }
}),

I'm expecting a way to make a condition of when the date is null

CodePudding user response:

if item.edited_on is a nullable field (i.e. datetime? instead of datetime) just check

if (item.edited_on != null)
{
    return Html.Raw(string.Format("{0:dd-MMM-yyyy}", item.edited_on));
}
else
{
    return Html.Raw(string.Format("Unavailable"));
}

if it is not nullable you can check it against default(DateTime):

if (item.edited_on !=  default(DateTime))
{
    return Html.Raw(string.Format("{0:dd-MMM-yyyy}", item.edited_on));
}
else
{
    return Html.Raw(string.Format("Unavailable"));
}
  • Related