Search code examples
c#razorasp.net-core-mvc

ASP.NET Core MVC if statement in view


ASP.NET Core MVC if statement in view

Is there a way to have an if statement change the text displayed in a field? I want to display "None" if the date field is 09/09/9999. Since date fields can't be null, I use that date to indicate no due date.

I tried this but get the error:

Cannot implicitly convert type string to System.DateTime.

Any help would be appreciated.

@if (@Convert.ToString(string.Format("{0:MM/dd/yyyy}", item.DueDate)) == "09/09/9999")
{
    item.DueDate = "None";
} else 
{
    @Convert.ToString(string.Format("{0:MM/dd/yyyy}", item.DueDate))
}

Solution

  • Declare it as nullable:

     public DateTime? DueDate { get; set; }        
    

    and check in the view:

    @if (item.DueDate.HasValue)
    {
      @Convert.ToString(string.Format("{0:MM/dd/yyyy}", item.DueDate))  
    }
    else
    {
        @:None
    }
    

    With this syntax if the item.DueDate is not defined the None will be displayed.