What is Razor View Engine in Asp.Net mvc?

Razor view engine in asp.net mvc is the syntax that allows you to write server-side code on view. It helps to combine code and HTML in a fluid manner. Razor is not a new programming language. If you know C#, Vb.Net, and bit HTML, you can easily write Razor code. Razor supports C# and Visual Basic programming languages.


The Razor syntax is based on C# programming language, and the code statements in Razor end with a semicolon (;) that would be like as shown below. 

Syntax of Razor View Engine

Generally, in razor view engine code blocks are enclosed in "@{ ... }". Here “@” is a character that tells the beginning of Razor syntax. This code can be a single expression or an entire code block. Following syntax represents a razor view engine declaration in asp.net mvc.




//Razor block



In the above code, the "@{" character tells the beginning of the block, and the"}" character tells the ending of the block.

Declaring Variable in Razor View

In the razor view engine, we will declare a variable like as shown below.



var weekDay = DateTime.Now.DayOfWeek;


Types of Block Statements in Razor

In razor, we have a different type of block statements available. Those are 

Single Statement Block and Inline Expression

As we discussed earlier, we will define code in opening and closing curly brackets @{...} and single statement block code will be like as shown following.



@{var Series = 4 ;}

@{var RazorMessage = "Hello Razor";}

<p> MVC series : @Series</p>


<p> Razor Message : @RazorMessage</p>


Multiple Statement Block and Inline Expression

In multiple statements block, we will define all variables in single curly brackets @{...}, so we need to end each variable with a semicolon. Our multiple statement block code will be as shown below.



    var Title = "Welcome to Razor syntax!";

    var weekDay = DateTime.Now.DayOfWeek;

    var HomeMessage = Title + " Today is: " + weekDay;



<p> Razor Message : @HomeMessage</p>

Generally, in razor engine code written at the top of view will be accessible in any other code block in same view page else in case if we declare a variable in middle and try to access a top we will not be able to access that variable and it will throw an error like as shown following.


access variables in razor view engine in asp.net mvc

If we observe the above code, we tried to access variable "i" before declaring that's the reason it throws error like as shown above.