Search⌘ K
AI Features

Adding Conditional Content

Explore how to use conditional statements in Razor templates to dynamically control HTML output in ASP.NET Core MVC. Understand the correct use of C# if, else, else if, and switch statements alongside HTML, managing null values, and the syntax rules between HTML and C# modes. Master the implementation of conditional sections in layout pages to optimize content like JavaScript or CSS references. This lesson helps you create adaptable, clean, and maintainable web UI content tailored to your data.

Conditional statements

Sometimes filling holes in HTML with variable content is not enough to adapt the HTML to our data. We might need to include some HTML only if some conditions are met. A typical example is the proper handling of null values or empty lists:

HTML
@if(customer != null)
{
<div class="@myDynamicCssClass">
<p>
Name: @customer.Name
</p>
<p>
Surname: @customer.Surname
</p>
<p>
Age: @((new DateTime(1,1,1)+(DateTime.Today-customer.DateOfBirth)).Year-1)
<p>
</div>
}

Conditional content may be provided with a usual C# if statement and precedes with an @ symbol. Similar to the case of C# expressions, the @ symbol informs the Razor compiler that we are passing from HTML syntax to C# syntax.

We may also add an else branch:

HTML
@if(customer != null)
{
<div class="@myDynamicCssClass">
<p>
Name: @customer.Name
</p>
<p>
Surname: @customer.Surname
</p>
<p>
Age: @((new DateTime(1,1,1)+(DateTime.Today-customer.DateOfBirth)).Year-1)
<p>
</div>
}
else
{
<p>No customer provided!</p>
}

We may also add else if branches, so the general statement format is:

HTML
@if(...)
{
...
}
else if
{
...
}
...
else
{
...
}

Razor syntax also supports the switch statement:

HTML
@if(customer.DateOfBirth.HasValue)
{
<p>
@switch (customer.DateOfBirth.Value.DayOfWeek)
{
case DayOfWeek.Monday:
<strong>Born on Monday</strong>
break;
case DayOfWeek.Tuesday:
<strong>Born on Tuesday</strong>
break;
case DayOfWeek.Wednesday:
<strong>Born on Wednesday</strong>
break;
case DayOfWeek.Thursday:
<strong>Born on Thursday</strong>
break;
case DayOfWeek.Friday:
<strong>Born on Friday</strong>
break;
case DayOfWeek.Saturday:
<strong>Born on Saturday</strong>
break;
default:
<strong>Born on Sunday</strong>
break;
}
</p>
}

The content between the { and } symbols of the if branches and the content after each case of the switch can be a mix of C# code and HTML. In the previous examples, we started ...