a blog for those who code

Saturday 18 March 2017

Getting Started with Razor Syntax in ASP.NET MVC

In this post we will be discussing about getting started with Razor View Engine or Razor Syntax in Asp.Net MVC. Razor Syntax helps us to combine code and markup in the views. In simple terms Razor is a markup syntax that lets you to embed server-based code (i.e. C#) into web pages.
Don't think razor as a new programming language but it uses C# syntax for embedding code in a page.


ALSO READ : Validate Errors on Compile Time in ASP.Net MVC Razor View

Razor Basic Syntax (Uses the @ character)


Single Statement Block

Razor code can be inserted anywhere within HTML code. Razor code blocks are enclosed in @{...}.
@{ var a = 1; }
Multi Statement Block
@{
 var a = 1;
 var b = 1;
 var c = a + b;
}
Add Comments

Razor has its own component syntax for comments which begins with @* and ends with *@
@* This is a Comment
   can be spread over multi line *@
You can also use comments within a code block as shown below
@{
  // Variable a
  var a = 1;
}
Conditional Statements 

Razor is smart enough to know that if there an opening bracket there must be a closing bracket.
@if()
{
 // Code
}
else
{
  // Code
}
Display HTML within Razor Code block

We have to use @: or <text>...</text> to make Razor understand that its an HTML inside Code block as shown below
@{
 var a = 1;
 @:<p> Hello </p>
}
@{
 var a = 1;
 <text>
   Hello
   <br />
   CodingDefined
 </text>
}
Escape @ character

If you want to escape @ character in View you have to add one more @ sign as shown below
<p> @@CodingDefined.com </p>

No comments:

Post a Comment