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.comand knows it is an email. - Write
@@for one@. For example,@@RavisTeaShopshows@RavisTeaShop.
- Change
@@RavisTeaShopto@RavisTeaShopand wait a moment. A red line appears, because Razor now looks for a C# name calledRavisTeaShop.
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
.razorfile, 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). privatemeans 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
cupsto4and press ▶ Run. The total changes, becauseGetTotal()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 * 2shows3 * 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)
@ifshows its HTML only when the condition istrue.else ifchecks another condition.elseruns 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)
@switchpicks one case from many, based on one value.- Each
caseends withbreak;.defaultruns when no case matches. - It is neater than a long chain of
else ifwhen you compare one value.
Loops (@foreach, @for, @while, @do)
A loop repeats HTML. Razor has four kinds:
| Loop | Use it when |
|---|---|
@foreach | You have a list and want one item of HTML per entry. The most common one. |
@for | You want to count, for example from 1 to 5. |
@while | You repeat while a condition is true. |
@do | Like 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
@doloop.triesstarts at 5, sotries < 3is false. It still runs once, becausedochecks 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.@pageis one you already know. @usinglets the file use classes from a namespace (a group of classes). For example,@using System.Textgives youStringBuilder, which joins many pieces of text into one.@namespaceputs 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.Textline. A red line appears underStringBuilder, 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, notBlazorApp.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
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
@cups * 2 to do maths | Razor reads the whole line as C# | Write @(cups * 2) | The page shows 3 * 2 |
Typing @ for a real at sign before a word | One @ is just text | Write @@ | Razor looks for a C# name and shows an error |
Showing user text with MarkupString | It is just text | Use MarkupString only for your own HTML | Harmful HTML or scripts can run |
HTML outside the braces of @if | Razor knows which lines belong to the @if | Put the HTML inside { } | The HTML always shows |
Missing break; in a @switch case | Cases stop by themselves | End every case with break; | A build error |
| Using an HTML comment for private notes | <!-- --> is hidden | Use @* *@ | 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.@nameis an implicit expression.@( )is explicit: use it for spaces and maths.MarkupStringshows raw HTML. Use it only for HTML you wrote.@if,@switchand loops choose and repeat HTML.@* *@comments never reach the browser.@usingbrings in a namespace.
Next: Components Basics