Krishan Dutt Sharma

Web Developer

Razor View Engine in MVC.

Today, in this Article we learn about the Razor View Engine.

Overview

Razor  Engine is an advance view engine that was introduced with MVC 3. This is not a new language but it is a new markup syntax. Ths namespace for razor engine is System.Web.Razor. The file extension used with Razor Engine is different from web form Engine. It has  .cshtml or  .vbhtml extension for View, Partial View, editor template and for layout pages. “Razor” was in development beginning in June 2010 and was released for Microsoft Visual Studio in January 2011.

Razor Syntax 

Razor Support both C# and VB.

Razor Syntax Rule for C#

  • Razor code blocks are enclosed in @{…..}.
  • Inline expressions (Variables and function) start with @.
  • Code statement end with a semicolon.
  • variables are declared with the var keyword.
  • Strings are enclosed with quotation marks.
  • C# code is case sensitive.
  • C# files have the extension .cshtml.

C# Example 

<!-- Single statemant block -->
@{ Var myMessage ="Hello, This is Krishan Dutt."}
<!-- Inline expression or Variable -->
<p> The Value of 2+2 is : @valofSum</p>
<!-- Multi-Statement block -->
@{
   Var ValofSum=4;
   Var weekDay=Datetime.Now.DayOfWeek;
   Var Msg= "Value of 2+2 is :"+ValofSum + at +weekDay;

}
<p>msg</p>

Razor Syntax Rule for VB

  • Razor code blocks are enclosed in @Code … End Code
  • Inline expressions (variables and functions) start with @
  • Variables are declared with the Dim keyword
  • Strings are enclosed with quotation marks
  • VB code is not case sensitive
  • VB files have the extension .vbhtml
<!-- Single statemant block -->
@Code Var myMessage ="Hello, This is Krishan Dutt." End Code
<!-- Inline expression or Variable -->
<p> The Value of 2+2 is : @valofSum</p>
<!-- Multi-Statement block -->
@Code
Var ValofSum=4;
Var weekDay=Datetime.Now.DayOfWeek;
Var Msg= "Value of 2+2 is :"+ValofSum + at +weekDay;
End Code
<p>msg</p>

To understand the Razor View Engine we should learn its syntax so let’s start with the syntax.

  • Single Statement block and inline expression

Each code block will be start and end by opening and closing curly brackets {..} respectively. A statement is defined in a code block, in other words between the opening and closing curly brackets and ending with a semicolon (“;”). But when it’s used as an inline expression then it does not need to use a semicolon.

Razor-View-Engine-in-MVC-1.jpg

Output is :

Razor-View-Engine-in-MVC-2.jpg

  • Multi-Statement block 

We can also define a multiline statement block as a single-line statement block. In a multiline statement block, we can define multiple code statements and can process data. A multiline block will exist between the opening and closing curly braces but the opening brace will have the “@” character in the same line if we define the “@” and opening curly braces in different lines then it will generate an error.

Razor-View-Engine-in-MVC-3.jpg

Output is :

Razor-View-Engine-in-MVC-4.jpg

  • Conditional Statements

We can create a dynamic web page in Razor View Engine as condition based. We can define a condition inside a code block or outside the code block. The If statement works the same as it does in other programming languages.

Razor-View-Engine-in-MVC-5.jpg

It is a default rule that a block statement or statements must exist within curly braces even if the block has a single statement. In the code block above we have two types of if conditions, one is inside code block so the @ character is used with code blocks starting braces and another is outside the code block so the @character is used with an if. Finally, we get the output of these two if statements.

Razor-View-Engine-in-MVC-6.jpg

  • Looping

All loops work the same as in other programming languages, we can define looping inside a code or outside a code block. We can define a for, do while or while loop in a code block and use the same syntax for initialization, increment/decrement and to check a condition.

Razor-View-Engine-in-MVC-7.jpg

We can also define a for-each in a code block that accesses data forwardly from any collection. The code block above has both for and for-each statements and their output is:

Razor-View-Engine-in-MVC-8.jpg

  • Switch case the conditional operator
@switch (fileName) 
{ 
   case "itfunda": 
   <p>itfunda logo</p> 
   break; 
   case "dotnetfunda": 
   <p>dotnetfunda logo</p> 
   break; 
   default : 
   <p>no logo</p> 
   break;
 }
  • Variable data inside URL
<img src="http://www.dotnetfunda.com/images/@(fileName).gif" /> 
  • Custom helper method

Sometimes, we need to create a custom helper method in the Razor to avoid the duplication of the code. To do that we can use @helper markup followed by the name of the method and parameters if any.

@helper AddSalutation(string name)
 {  
   <b>Mr. @name</b>
 }

To call this helper method, we can call it as if it is any other method defined in Razor server-side block.

<li>Inline Helper Method Output: @AddSalutation("Sheo Narayan")</li> 

The output of AddSalutation method will be “Mr. Sheo Narayan“.

  • Comments

Razor View Engine has two types of comments, one is single-line and another is multiline. Razor uses the syntax “@* ..*@” for the comment block but in a C# code block we can also use “/* */” or “//”. HTML comments are the same, “<!– –>”.

Razor-View-Engine-in-MVC-9.jpg

  • Use of Object

We can also use an object in both a code block and HTML using razor syntax.

Razor-View-Engine-in-MVC-10.jpg

Here we used a Date object of the C# language and access the properties of its. The result of the Date object in the code above is:

Razor-View-Engine-in-MVC-11.jpg

So we have a rule of thumb that C# code is used in a code block that starts with “@{” and ends with “}” and whenever a variable is used in an HTML block then the variable is used with the prefix “@”.

It is not a complete list of razor syntax but I think that you now have the basic syntax of razor so we should proceed to an example.

How Does it Work?

Razor is a simple programming syntax for embedding server code in web pages.

Razor syntax is based on the ASP.NET framework, the part of the Microsoft.NET Framework that’s specifically designed for creating web applications.

The Razor syntax gives you all the power of ASP.NET, but is using a simplified syntax that’s easier to learn if you’re a beginner, and makes you more productive if you’re an expert.

Razor web pages can be described as HTML pages with two kinds of content: HTML content and Razor code.

When the server reads the page, it runs the Razor code first, before it sends the HTML page to the browser. The code that is executed on the server can perform tasks that cannot be done in the browser, for example accessing a server database. Server code can create dynamic HTML content on the fly before it is sent to the browser. Seen from the browser, the HTML generated by server code is no different than static HTML content.

Reading User Input

Another important feature of dynamic web pages is that you can read user input.

Input is read by the Request[] function, and posting (input) is tested by the IsPost condition:

@{
var totalMessage = "";
if(IsPost)
    {
    var num1 = Request["text1"];
    var num2 = Request["text2"];
    var total = num1.AsInt() + num2.AsInt();
    totalMessage = "Total = " + total;
    }
}
<html>
<body style="background-color: beige; font-family: Verdana, Arial;">
<form action="" method="post">
<p><label for="text1">First Number:</label><br>
<input type="text" name="text1" /></p>
<p><label for="text2">Second Number:</label><br>
<input type="text" name="text2" /></p>
<p><input type="submit" value=" Add " /></p>
</form>
<p>@totalMessage</p>
</body>
</html>