Razor syntax
Razor syntax is made up of HTML, Razor markup, and C#. Rendering HTML from a Razor component is the same as rendering HTML from an HTML file. The HTML in a Razor component is rendered by the server unchanged. Razor syntax uses both inline expressions and control structures.
Inline expressions
Inline expressions start with an @
symbol followed by a variable or function name. This is an example of an inline expression:
<h1>Blazor is @Text!</h1>
Control structures
Control structures also start with an @
symbol. The content within the curly brackets is evaluated and rendered to the output. This is an example of an if
statement from the FetchData
component in the Demo
project:
@if (forecasts == null) { <p><em>Loading...</em></p> }
Each code statement within a Razor code block must end with a semicolon. C# code is case sensitive and strings must be enclosed in quotation marks.
Conditionals
The following types of conditionals are included in Razor syntax:
if
statementsswitch
statements
This is an example of an if
statement:
@if (DateTime.Now.DayOfWeek.ToString() != "Friday") { <p>Today is not Friday.</p> } else if (DateTime.Now.Day != 13) { <p>Today is not the 13th.</p> } else { <p>Today is Friday the 13th.</p> }
The preceding code uses an if statement to check it the current day of the week is Friday and/or the current day of the month is the 13th.
This is an example of a switch
statement:
@switch (value) { case 1: <p>The value is 1!</p> break; case 42: <p>Your number is 42!</p> break; default: <p>Your number was not 1 or 42.</p> break; } @code { private int value = 2; }
The preceding switch
statement compares the value
variable to 1
and 42
.
Loops
The following types of loops are included in Razor syntax:
for
loopsforeach
loopswhile
loopsdo while
loops
Each of the following examples uses an array of the WeatherForecast
type. WeatherForecast
includes a Summary
property and is defined in the Demo
project.
This is an example of a for
loop:
@for (var i = 0; i < forecasts.Count(); i++) { <div> forecasts[i].Summary</div> }; @code { private WeatherForecast[] forecasts; }
This is an example of a foreach
loop:
@foreach (var forecast in forecasts) { <div>@forecast.Summary</div> }; @code { private WeatherForecast[] forecasts; }
This is an example of a while
loop:
@while (i < forecasts.Count()) { <div>@forecasts[i].Summary</div> i++; }; @code { private WeatherForecast[] forecasts; private int i = 0; }
This is an example of a do while
loop:
@do { <div>@forecasts[i].Summary</div> i++; } while (i < forecasts.Count()); @code { private WeatherForecast[] forecasts; private int i = 0; }
Razor syntax is easy to learn if you already know C#. It includes both inline expressions and control structures such as conditionals and loops.