What is Razor View Engine in Asp.Net mvc?

Razor view engine in asp.net mvc is syntax that allows you to write server side code on view. It helps to combine code and html in 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 character that tells beginning of Razor syntax. This code can be a single expression or entire code block. Following syntax represents razor view engine declaration in asp.net mvc 




//Razor block



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

Declaring variable in Razor View

In razor view engine we will declare variable like as shown below 



var weekDay = DateTime.Now.DayOfWeek;


Types of Block Statements in Razor

In razor we have different type of block statements available those are 

Single Statement Block and Inline Expression

As we said 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 statement block we will define all variables in single curly brackets @{...} so we need to end each variable with semicolon and our multiple statement block code will be like 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 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 able to access that variable and it will throw error like as shown following


access variables in razor view engine in asp.net mvc

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

Topics Covered