0

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))
}
3
  • How the DueDate is declared? Is it DateTime DueDate { get; set; }? Commented Oct 28, 2022 at 16:41
  • Date fields can be null if you declare them as nullable: public DateTime? DueDate { get; set; } Commented Oct 28, 2022 at 16:49
  • Oh sorry forgot to include that. [DataType(DataType.Date)] public DateTime DueDate { get; set; } = new DateTime(9999, 09, 09); Commented Oct 28, 2022 at 17:23

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.