Razor Syntax

By Syncfusion®, Inc. · Last updated

How Razor mixes HTML and C#: the @ symbol and escaping it, @code blocks with variables and methods, implicit and explicit expressions, raw HTML with MarkupString, @if, @switch and loops, comments, @using and @namespace.

What you will learn

  • Use @ to put C# values into HTML, and @@ to show a real @
  • Write variables and methods in an @code block
  • Choose between implicit and explicit expressions
  • Show or repeat HTML with @if, @switch and loops
  • Use Razor comments, @using and @namespace

Razor Overview

  • Razor is the way you write Blazor components.
  • A Razor file ends in .razor. It mixes HTML (what the page shows) with C# (the logic).
  • The @ sign tells Razor: "this part is C#, not HTML".
  • When the app runs, Razor works out the C# parts. Then it turns the whole file into plain HTML for the browser.

Real-World Example:

  • Ravi's order page shows today's date, the customer's name and the total price.
  • These values change every time.
  • With Razor, he writes the HTML once and drops C# values into it with @.

Press ▶ Run. Each @ value becomes plain text in the page.

Watch the animation. Razor replaces each @ part with its value. The browser only ever sees HTML.

Animation: the line Order for @customer goes into Razor. Razor replaces @customer with Asha. The browser gets Order for Asha as plain HTML.

Your .razor file

Order for @customer

Razor works out the @ What the browser gets

Order for Asha

customer = "Asha"

@customer is C#. Razor swaps it for its value, so the browser gets plain HTML.

Simple lesson: Razor is HTML plus C#. The @ sign marks the C# parts.

Razor Basics

The @ Symbol

  • @ switches from HTML to C#.
  • After the C# part ends, Razor goes back to HTML by itself.
  • You can use @ for a value (@tea), a C# keyword (@if, @foreach) or a directive (@page, @using).

Escaping @

Sometimes you want a real @ sign on the page. There are two easy ways:

  • Email addresses work as they are. Razor sees ravi@teashop.com and knows it is an email.
  • Write @@ for one @. For example, @@RavisTeaShop shows @RavisTeaShop.
  • Change @@RavisTeaShop to @RavisTeaShop and wait a moment. A red line appears, because Razor now looks for a C# name called RavisTeaShop.

Quick rule: @ followed by a name means C#. If you want the @ sign itself, type it twice: @@.

Simple lesson: @ starts C#. Use @@ when you want to show the @ sign.

Code Blocks

@code Block

  • @code { } holds the C# for your component.
  • Put it at the bottom of the .razor file, after the HTML.
  • Everything inside it belongs to this component only.

Variables

  • A variable is a named box that holds a value, like cups = 2.
  • Write the type, the name and the value: private int cups = 2;
  • Common types: string (text), int (whole number), decimal (money), bool (true or false).
  • private means only this component can use it.

Methods

  • A method is a named set of steps. You can run it again and again.
  • A method can return a value. GetTotal() below returns the price for all cups.
  • Use a method in HTML with @, like @GetTotal().
  • Change cups to 4 and press ▶ Run. The total changes, because GetTotal() works it out again.

Simple lesson: Keep your variables and methods in @code { }. Use them in the HTML with @.

Razor Expressions

An expression is a piece of C# that gives a value, like cups or cups * pricePerCup.

Implicit Expressions

  • Implicit = @ followed straight by a name: @tea, @tea.Length, @GetTotal().
  • Razor reads the name, dots and brackets, then stops at the first space.
  • That makes it short and easy to read.

Explicit Expressions

  • Explicit = @( ... ) with round brackets.
  • Use it when the expression has spaces or maths, like @(cups * pricePerCup).
  • Without the brackets, @cups * 2 shows 3 * 2. Razor stops reading at the space.

Watch the animation. Razor stops at the space in the first line. The brackets in the second line tell it where the C# ends.

Animation: in @cups * 2, a highlight covers only @cups and stops at the space, so the page shows 3 * 2. In @(cups * 2), the highlight covers everything inside the brackets, so the page shows 6. Implicit

@cups * 2 page shows:

3 * 2 Explicit

@(cups * 2) page shows:

6

Implicit stops at a space. Explicit reads everything inside the brackets.

Raw HTML (MarkupString)

  • By default, Razor shows text as text. If a variable holds <b>Hot!</b>, the page shows the tags as letters.
  • This keeps your page safe. Text from a user cannot add its own HTML or scripts.
  • To show it as real HTML, wrap it in MarkupString: @((MarkupString)offer).

Use MarkupString only for HTML you wrote. Never use it for text that users type, such as a review or a name. That text could hide harmful code.

Simple lesson: Use @name for simple values and @( ) for spaces or maths. Use MarkupString only for your own HTML.

Control Flow

Control flow decides which HTML is shown, and how many times. You use normal C# keywords with @ in front.

Conditionals (@if, @else if, @else)

  • @if shows its HTML only when the condition is true.
  • else if checks another condition. else runs when nothing above matched.
  • The HTML goes inside the curly braces { }.

Animation: the value of stock goes into a check. If stock is 0, Sold out is shown. Else if stock is less than 5, Only a few left is shown. Else, In stock is shown. The highlight moves between the three answers as stock changes from 0 to 3 to 20.

stock =

0

3 20

@if / else

stock == 0 → Sold out

stock < 5 → Only a few left

else → In stock

Razor checks each condition from the top. The first one that is true wins.

  • Click Sell one cup a few times. The message changes from In stock to Only … left to Sold out.

Switch (@switch)

  • @switch picks one case from many, based on one value.
  • Each case ends with break;. default runs when no case matches.
  • It is neater than a long chain of else if when you compare one value.

Loops (@foreach, @for, @while, @do)

A loop repeats HTML. Razor has four kinds:

LoopUse it when
@foreachYou have a list and want one item of HTML per entry. The most common one.
@forYou want to count, for example from 1 to 5.
@whileYou repeat while a condition is true.
@doLike while, but it always runs at least once.

Animation: a list with Masala, Ginger and Lemon. @foreach picks each one in turn, and a new list item appears on the page for each. menu

"Masala"

"Ginger"

"Lemon"

@foreach

Page

• Masala

• Ginger

• Lemon

@foreach takes each item in turn and adds its HTML to the page.

  • Look at the @do loop. tries starts at 5, so tries < 3 is false. It still runs once, because do checks the condition at the end.
  • @{ ... } is a small C# block inside the HTML. Here it makes a variable just for that loop.

Simple lesson: Use @if and @switch to choose what to show, and loops to repeat it. Put the HTML inside { }.

Directives and Comments

Comments (@* *@)

  • A comment is a note for people. It is not part of the page.
  • Razor comments look like @* your note *@.
  • They never reach the browser. HTML comments (<!-- -->) are sent to the browser, so anyone can read them with "View source".

Inside @code { }, you write normal C# comments: // one line or /* many lines */.

@using and @namespace

  • A directive is a special line that starts with @. It sets something up for the whole file. @page is one you already know.
  • @using lets the file use classes from a namespace (a group of classes). For example, @using System.Text gives you StringBuilder, which joins many pieces of text into one.
  • @namespace puts this component in a namespace you choose. Most of the time you do not need it. Blazor uses the folder names.
  • Delete the @using System.Text line. A red line appears under StringBuilder, because the file can no longer find it.
  • Put it back, and the red line goes away.

Here is @namespace in a real file. You will rarely need it:

  • This component's full name is now BlazorApp.Shop.Menu, not BlazorApp.Components.Pages.Menu.
  • To use it from another folder, that file needs @using BlazorApp.Shop.

Simple lesson: @* *@ hides notes from the browser. @using brings in classes. @namespace sets where your component lives.

Common mistakes

MistakeWrong ideaCorrect ideaWhat goes wrong
@cups * 2 to do mathsRazor reads the whole line as C#Write @(cups * 2)The page shows 3 * 2
Typing @ for a real at sign before a wordOne @ is just textWrite @@Razor looks for a C# name and shows an error
Showing user text with MarkupStringIt is just textUse MarkupString only for your own HTMLHarmful HTML or scripts can run
HTML outside the braces of @ifRazor knows which lines belong to the @ifPut the HTML inside { }The HTML always shows
Missing break; in a @switch caseCases stop by themselvesEnd every case with break;A build error
Using an HTML comment for private notes<!-- --> is hiddenUse @* *@Anyone can read it with View source

Check Yourself

Exercises

What to Remember

  • Razor mixes HTML and C#. @ starts the C# part. @@ shows a real @.
  • @code { } holds variables and methods.
  • @name is an implicit expression. @( ) is explicit: use it for spaces and maths.
  • MarkupString shows raw HTML. Use it only for HTML you wrote.
  • @if, @switch and loops choose and repeat HTML.
  • @* *@ comments never reach the browser. @using brings in a namespace.

Next: Components Basics