...

/

Adding Conditional Content

Adding Conditional Content

In this lesson, we will add conditional content to Razor templates.

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:

Press + to interact
@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:

Press + to interact
@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:

Press + to interact
@if(...)
{
...
}
else if
{
...
}
...
else
{
...
}

Razor syntax also supports the switch statement:

Press + to interact
@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 ...