Razor View Engine & Razor Syntax in ASP.NET Core

In this Razor tutorial, we will take a quick tour of the Razor View Engine in ASP.NET Core MVC. The Razor makes it easier to embed the C# code inside the HTML, thus providing the ability to generate the dynamic response. In this tutorial, we will explore the Razor syntax.

What is View Engine

The View Engine is responsible for producing an HTML response when invoked by the Controller Action method.

The Controller Action methods can return various types of responses, which are collectively called as Action Results. The ViewResult is the ActionResult which produces the HTML Response.

The ViewResults are produced by the View Engine. When the Controller Action method invokes the view() or PartivalView(), it invokes the View Engine, which produces the HTML Response.

What is Razor View Engine

The Razor View Engine is the default View Engine for the ASP.NET Core apps. It looks for Razor markup in the View File and parses it and produces the HTML response.

The Razor Markup

The Controller in MVC invokes the View by passing the data to render. The Views must have the ability to process the data and generate a response. This is done using the Razor markup, which allows us to use C# code in an HTML file. The Razor View Engine process these markups to generate the HTML.

The files containing Razor markup generally have a .cshtml file extension.

The Razor syntax is shorter and simpler and easy to learn as it uses the C# or visual basic. The Visual Studio IntelliSense support also helps with Razor syntax.

Example Project

To know how Razor works create an Empty Project and add MVC Middlewares and services. You can refer to the tutorial Building ASP.NET Core Application.

You can download the source code from the GitHub. The initial Code is in the folder Start and the completed code in the folder Razor

Goto the index method of the HomeController

Open the index.cshtml and copy the following code.

Run the app and you should see Razor Example in the browser.

Now, go to the Models Folder and create a new class Customer.cs.

The Razor Syntax

The Razor uses the @ symbol to transition from HTML markup to the C# code.The following are the two ways, by which you can achieve the transitions.

  • Using Razor code expressions
  • Using Razor code blocks.

These expressions are evaluated by the Razor View Engine and written to the response.

Razor Code blocks

The Razor code blocks start with @ symbol followed by curly braces. You can use code blocks anywhere in the markup.

A Razor code block can be used manipulate a model, declare variables, and set local properties on a view etc. However, you should not use it for business logic.

Now, Open the index.html and copy the following code.

First, we have created a Razor code block beginning with a @ symbol and { } curly brackets. Inside the Curly brackets, we have a regular C# code,  which declares a  greeting & weekDay Variable.

The Second Razor Code block creates a cust variable, which is a new instance of the Customer model.

Razor Code Expressions

The Razor Code expressions start with @ and followed by C# code. The Code expression can be either Implicit or Explicit.

Implicit Razor Expressions

Implicit Razor expressions start with @ followed by C# code like the one mentioned above.

In the following example, the code @greeting@DateTime.Now@WeekDay are treated as Implicit Razor expressions. Space is not allowed in the Code expression, as it is used to identify the end of the expression. The expressions are evaluated by the Razor View engine and the result is inserted in their place.

The following Razor code expression displays name and address inside the <p> tag.

Explicit Razor Expressions

Explicit Razor expressions start with @ followed by (). Any content within the () parenthesis is evaluated and rendered to the output.

IntelliSense support

The image below shows how the Razor markup is used inside an HTML page and the Intellisense support from the Visual Studio.

Intellisense Support for Razor in Visual Studio

Using Directive

The @using directive works similar to the  C# using directive and allows you to import namespaces. The MVCCoreApp.Models can be imported as shown below

And then we can simply use  var cust = new Customer() instead of var cust = new MVCCoreApp.Models.Customer()

Variable Declaration

The Variables are declared using the var keyword or using the c# data type. The int, float, decimal, bool, DateTime & string keywords can be used to store strings, numbers, and dates, etc.

The variables are inserted directly into a page using @.

Strings are enclosed in double quotation marks.

To use a double quotation mark inside the string, use a verbatim string literal.  The verbatim string is prefixed with the @ symbol and repeat the quotation mark.

Similarly, backslash character can be printed using the same technique.

You can print @ in HTML by repeating (Escape) the @ symbol as shown below.

The @ in the email address is correctly identifies by the Razor engine and does not to treat the @ as a code delimiter. You do not have to escape it with @.

Comments

Use @*   *@ to place comments

HTML Elements inside code block

Any HTML Elements inside the Razor code block is correctly identified by the Razor engine as shown below.

Single line text

You can output the literal values without HTML element by prefixing it with @:

The @: used to define the single line of literal values

Multiline text

For the multiline text use the <text> </text> element

Conditional Statements

The Razor engine is able to process conditional statements like if & Switch statement.

If and Else Conditions

If Condition is used to render a section based on a condition as shown below.

Or you can use the following code

An If else if else block

Switch Statements

A switch statement can insert a section into HTML based on a number of conditions.

Loops

Foreach loop

The loops are used to repeat a code block for

The best use case of a foreach loop is to loop through a collection object and display the result inside table

While loop

HTML Encoding

All the Razor expressions are automatically HTML Encoded.

For Example

The above code will not result in an alert box. Instead, you will see the “<script>alert(‘You are under cross-site script injection attack’);</script>”  printed in the browser.

The Razor automatically encodes the < to &lt; and > to &gt;

If you look at the generated HTML Response you will see this

<span>&lt;script&gt;alert(&#x27; You are under cross-site script injection attack&#x27;) ;&lt;/script&gt; </span>

If you want to script to be executed, then you can use the @html.raw method to print out the unencoded string as shown below. This code results in an alert box popping up.

Summary

We looked at the Razor Syntax in this Tutorial. The Razor codes start with @ and you can either use a Razor expressions or Razor code blocks to insert C# code inside HTML Markup. This gives the programmers the ability to create a dynamic web page using C# features like conditional statements, loops etc.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top