ASP.NET Razor View Engine Syntax Overview

Razor File Types

Razor templates support two primary file extensions: .cshtml for C# server code and .vbhtml for VB.NET server code. These files combine server-side logic with HTML markup, similar to .aspx pages without code-behind files.

The @ Symbol

The @ character initiates Razor server code blocks and enables variable output directly in HTML:

@{
    string itemDescription = "Desk Lamp";
}
<span>@itemDescription</span>
<span>@DateTime.Now.ToString("yyyy-MM-dd")</span>

Code Blocks

Use @{} to define code sections containing server-side logic:

@{
    int valueA = 15;
    int valueB = 8;
    int total = valueA + valueB;
    @total
}

Alternatively, output expression results directly with @():

@(valueA + valueB)

Mixed Code and Markup

Razor enables seamless integrasion of server code and HTML:

@{
    int firstValue = 12;
    int secondValue = 7;
    int result = firstValue + secondValue;
    string textColor = "Blue";
    <span style="color: @textColor">@result</span>
}

Special Output Cases

  • Escape @ symbol: @@
  • Email addresses: Razor auto-detects emails, or use @:user@domain.com
  • Raw HTML output: @Html.Raw("<strong>text</strong>")
  • HTML-encoded output: @("<strong>text</strong>")

Commenting

Razor supports multiple commenting styles:

@* 
    Multi-line Razor comments
    <div>Commented HTML</div>
*@

@{ 
    // Single-line C# comment
    /* Multi-line C# comment */
}

Tags: ASP.NET razor C# html WebDevelopment

Posted on Sat, 23 May 2026 18:59:53 +0000 by rallen102