Learning Razor syntax
One of the things I like about the Razor syntax is that it is easy to mix code and HTML tags. By having the code close to the markup, it is, in my opinion, easier to follow and understand. The syntax is very fluid; the razor parser understands when the code stops and markup begins, which means we don’t need to think about it that much. It is also not a new language; instead, we can leverage our existing C# and HTML knowledge to create our components. This section will contain a lot of theory to help us understand the Razor syntax.
To transition from HTML to code (C#), we use the @
symbol. There are a handful of ways we can add code to our file, which we’ll explore in the following sections:
- Razor code blocks
- Implicit Razor expressions
- Explicit Razor expressions
- Expression encoding
- Directives
Razor code blocks
We have already seen some code blocks. A code block looks like this:
@code {
...