THE BEST WEB DEVELOPER SITE

ASP.NET Web Pages - Adding Razor Code


ASP.NET Web Pages use Razor markup with C# or VB code


Razor Markup

Razor is a simple markup syntax for embedding server code (C# or VB) into ASP.NET web pages.

Example

<!DOCTYPE html>

<html lang="en">
<head>
     <meta charset="utf-8" />
     <title>Web Pages Demo</title>
</head>
<body>
     <h1>Hello Web Pages</h1>
     <p>The time is @DateTime.Now</p>
</body>
</html>
Run example »

The page above contains both ordinary HTML markup and Razor markup.


Razor Syntax for C#

  • C# code blocks are enclosed in @{ ... }
  • Inline expressions (variables or functions) start with @
  • Code statements end with 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 statement block -->
@{ var myMessage = "Hello World"; }

<!-- Inline expression or variable -->
<p>The value of myMessage is: @myMessage</p>

<!-- Multi-statement block -->
@{
var greeting = "Welcome to our site!";
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + " Today is: " + weekDay;
}

<p>The greeting is: @greetingMessage</p>
Run example »

Razor Syntax for VB

  • VB code blocks are enclosed in @Code ... End Code
  • Inline expressions (variables or 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

VB Example

<!-- Single statement block  --> 
@Code dim myMessage = "Hello World" End Code
 
<!-- Inline expression or variable --> 
<p>The value of myMessage is: @myMessage</p> 
 
<!-- Multi-statement block --> 
@Code
dim greeting = "Welcome to our site!" 
dim weekDay = DateTime.Now.DayOfWeek 
dim greetingMessage = greeting & " Today is: " & weekDay
End Code


<p>The greeting is: @greetingMessage</p>
Run example »

More About C# and Visual Basic

If you want to learn more about Razor, and the C# and Visual Basic programming languages:

Go to the Razor section of this tutorial.