Skip to main content

Razor syntax in MVC

Razor is a simple syntax view engine which consists of razor syntax, c# and html to create dynamic web pages.
Razor uses @ symbol to transition from HTML to C#.

Implicit Razor expressions

Implicit Razor expressions start with @ followed by C# code. for example:
@DateTime.Now

Explicit Razor expressions

Explicit Razor expressions consist of an @ symbol with balanced parenthesis. For example
4+5=@(4 + 5)

Razor code blocks

Razor code blocks start with @ and are enclosed by {}. Unlike expressions, C# code inside code blocks is NOT rendered.
@{
      var msg = "hello world";
}
Html output: @msg

Implicit transitions

Within code blocks, you can even write the HTML markup with contents, which transition back into rendering HTML.
@{
      var implicitCodeBlockMsg = "hello world";
      <p>Html output: @implicitCodeBlockMsg</p>
}

Explicit transition

Within a code block, sometimes you want to render some code block as HTML without using html markup.
There are two ways to achieve this
1. Wrap the contents which you want to render as HTML with <text> tag, for example
 @{
       var explicitDTCodeBlockMsg = "hello world";
       <text>Html output: @explicitDTCodeBlockMsg</text>
}

2. Use the @: syntax, to render the line as HTML inside a code block.
@{
       var explicitLTCodeBlockMsg = "hello world";
       @:Html output: @explicitLTCodeBlockMsg
}

In short Razor view engine have Razor expression for C# only  and Razor code blocks for C# and HTML.

Control Structure

 In C# language we can control the flow of the program using control structures like if, for etc.
Razor engine support all the control structures supported by C# language.

Conditionals @if, else if, else and @switch

Below syntax help you to understand how to add conditionals operator in razor.

@if (condition)