Adding Conditional Content
In this lesson, we will add conditional content to Razor templates.
We'll cover the following...
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:
@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:
@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:
@if(...){...}else if{...}...else{...}
Razor syntax also supports the switch
statement:
@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 ...