Razor beginner syntax

Razor beginner intro and syntax tutorial

Razor is a syntax used to build web pages within ASP.NET applications. In essence it’s a mix of Razor specific markup, C# (or VB) and HTML code. In this guide I’m going to introduce you to Razor syntax, explain how it works and show you some other related stuff.

It’s worth noting that Razor syntax is pretty simple. Visual Studio has syntax highlighting for it as well as it supports Razor intellisense.

This guide is intended for ASP.NET Core, so some code samples may not work for ASP.NET MVC. Regardless, the principles remain the same.

It all starts with @ – implicit Razor expressions

First thing is what we call implicit Razor expression. It starts with an @. The most basic use case it to print out variables, properties or results of methods. Let’s start with a classic example, which is printing current date and time:

<span>@DateTime.Now</span>

The result, as we expected, is a current date and time enclosed within HTML span tags.

It’s short and easy, but you must remember that it calls ToString behind the scences so it is actually DateTime.Now.ToString(). It’s important because @ works on objects of all types.

In the same way you can render result of your own methods:

<p>@PageHelper.EstimatedReadTime()</p>

This however has some limitations. Not everything will be recognized, as the parser relies on spaces and special characters to recognized what is a valid syntax and when the code transitions to HTML.

One example of this would be the generic types. It won’t be recognized properly because the <> are going to be interpreted as a HTML tag. So this is not possible:

<b>@SomeClass.SomeMethod<string>("SomeParam")</b>

Another example of Razor limitations are spaces. When you put a space after implicit Razor expression it’s like an end to it. So it won’t recognize more complex code:

<b>@User.IsAdmin || User.IsMod</b>

In general, we can overcome limitations of implicit expressions by using explicit expressions.

Razor code blocks

Did you know you can embbed code blocks inside HTML? It’s a handy feature. All you need to do is to write your code inside a Razor code block, which is a @ sign followed by braces. Let me show you an example which defines a variable and renders it:

@{
    var firstName = "Zbigniew";
}
Hello <b>@firstName</b>!

This was a simple example, but since this is a C# code, we can do much more:

@{
    var today = DateTime.Now;
    var nextYear = new DateTime(today.Year + 1, 1, 1);
    var daysUntilNewYear = (nextYear - today).Days;
}
<p>Today is @today</p>
<p>Just @daysUntilNewYear more days to the next year</p>

Explicit Razor expressions

As you have seen in previous section you can actually execute C# code defined inside a view file. Sometimes however the code block is so short that we could skip it in favor of shorter expression. For this we can use explicit Razor expressions. In terms of syntax it’s a @ followed by parenthesis, inside which we put our code:

<p>Hey, don't you think that <u>@(new Random().Next())</u> is a funny number?</p>

Key point of explicit expressions is that everything in between parenthesis is evaluated and then the result of that evaluation is rendered.

Technically you could stuff a lot of code inside the parenthesis, but I prefer to keep explicit expressions to minimum (with short and understandable purpose). Otherwise it can quickly lead to overly complex code. Take a look at the following example, it calculates days until new year (same logic as in Razor code blocks section), but it’s hard to follow:

<p>Just @((new DateTime(DateTime.Now.Year + 1, 1, 1) - DateTime.Now).Days) more days to the next year</p>

HTML encoding

By default @ renders the output which is HTML encoded. This helps prevent XSS and HTML injection. Take a look how it works:

@{ var html = "Hello <b>World</b>";
<p>@html</p>

The code above will be rendered as:

<p>Hello <b>World</b></p>

However there may be occasions in which you want to render string as an HTML code, for example CMS with WYSIWYG editor which lets you format text. The solution for this is to use HtmlHelper.

As a side note, you can create custom classes which can help you create custom output with or without HTML tags. These are known as helpers. ASP.NET Core inlcudes a IHtmlHelper (and its implementation) which helps create some HTML, particulary for forms. It’s enabled in Razor and you can access it using Html variable.

This is how to render string with HTML contents:

@Html.Raw("Hello <b>World</b>")

Passing data from controller to view

Undoubtly you will want to pass some data from controller/action to a view file. There are a couple of ways of doing that.

ViewData / ViewBag

One way of transfering data to view is ViewData / ViewBag. ViewData is basically a dictionary. ViewBag is a dynamic wrapper around ViewData.

Take a look at this action, it passes some data to our view file:

public IActionResult About()
{
    ViewData["Message"] = "Hello world.";

    ViewBag.DisplayName = "software developer";

    return View();
}

Now, take a look how to render it in your view:

<h1>Hi @ViewBag.DisplayName</h1>
<p>@ViewData["Message"]</p>

ViewModel

The View method has an overload which lets us pass object to a view. We can create a new class for each action and make it available in view. One of the advantages of this (over the ViewData approach) is that we have strongly typed views.

This is a very basic explanation and an important concept. In this article I’m just trying to introduce you to things, so this will require some more reading and practice on your side.

Let’s see how the about page would look like if we used the view model approach:

public IActionResult About()
{
    var viewModel = new AboutViewModel
    {
        Message = "Hello world.",
        DisplayName = "software developer"
    };

    return View(viewModel);
}

Firstly, the object you passed can be accessed by the Model variable in your view file. But to achieve strong typing, we have to add @model AboutViewModel inside a view, which sets the page model type and allows us to access properties by name:

@model AboutViewModel
<h1>Hi @Model.DisplayName</h1>
<p>@Model.Message</p>

Flow control

At times we need to show something based on a specific condition. For this we use if, which is also handled by Razor. It blends nicely with HTML code so it’s pretty straightforward.

@if (User.HasPicture)
{
    <img src="@Url.Content(User.PicturePath)" alt="@User.Name avatar" />
}

<p>Welcome back @User.Name</p>

It also works with else and else if.

Loops

You will often need to process lists or arrays of data. It’s as easy in Razor as the controlling the flow. This is how you can render list of contacts using HTML unordered list:

<ul>
@foreach(var contact in Model.Contacts)
{
    <li>@contact.FullName - @contact.PhoneNumber</li>
}
</ul>

You can also use other types of loops.

Async

If you are wondering wheter or not you can use async methods in Razor views, then the answer is yes, you can. As everything else it’s pretty easy:

@await Html.PartialAsync("Notifications")

Tag Helpers

Another concept I’d like to introduce to you are the TagHelpers. In simple terms, you can create a class which will perform some actions on custom or existing HTML tags.

What’s interesting about them is that you don’t have to modify exising HTML code and, most of the times, you won’t even see them.

The most basic example I can think of is the built-in ImageTagHelper. Firstly it lets you resolve static image file path:

<img src="~/image/picture.png" />

Secondly, you can use it prevent browser image caching by appending file has to query string. The ImageTagHelper docs are located here. This is how to execute cache-busing functionality:

<img src="~/image/picture.png" asp-append-version="true" />

There are a lot of things which can be done with tag helpers. Here’s a list of random things you could do:

  • add specific CSS class to specific HTML tag
  • render a HTML structure
  • format content in between given tags or perform some operations on the data
  • parametrize output based on a data passed to tag (in a similar way as you use HTML attributes)
  • render complex HTML structure (for this I’d rather advise you to use ViewComponent)

Since this article is just and introduction to what you can do with Razor I won’t explain this further. Let me just point you to my other post about Extending built-in tag helpers.

Comments

We can comment code in Razor. Commented out code won’t be rendered by browser. There are no single-line comments, you can only use multi-line comments. You cannot create nested comments.

@*<p>This won't be rendered</p>*@
<p>Can you read this message?</p>
@*<b>@DateTime.Now</b>*@

Razor pages

There is also a thing called Razor Pages. This is not be confused with Razor syntax used strictly to render pages. While Razor Pages use Razor syntax, it’s more of an alternative to MVC. In a really basic terms it’s a different way of organizing your web app.