ASP.NET Web Pages - Add Razor Code

In this tutorial, we will use Razor markup through C# and Visual Basic code.

What is Razor?

  • Razor is a markup syntax for adding server-based code to web pages
  • Razor has the ability of traditional ASP.NET markup, but it is easier to learn and use
  • Razor is a server-side markup syntax similar to ASP and PHP
  • Razor supports the C# and Visual Basic programming languages

Add Razor Code

Remember the web page from the previous chapter:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8" />
    <title>Web Pages Demo</title>
</head>
<body>
    <h1>Hello Web Pages</h1>
</body>
</html>

Now add some Razor code to the example:

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 Instance

This page contains common HTML tags, in addition to: Razor code marked with @.

The entire work of Razor code is to detect the current time on the server and then display it. (You can specify format options, or simply display it in the default format)

The main Razor syntax rules in C#

  • Razor code blocks are enclosed by @{ ... }
  • Inline expressions (variables and functions) start with @
  • Code statements end with a semicolon
  • Variables are declared with the var keyword
  • Strings are enclosed with quotes
  • C# code is case-sensitive
  • The extension name of C# file is .cshtml

C# Example

<!-- Single-line code block -->
@{ var myMessage = "Hello World"; }
<!-- Inline expressions or variables -->
<p>The value of myMessage is: @myMessage</p> 
<!-- Multi-line code 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 Instance

Main Razor syntax rules in VB

  • Razor code blocks are enclosed with @Code ... End
  • Inline expressions (variables and functions) start with @
  • Variables are declared with the Dim keyword
  • Strings are enclosed with quotes
  • C# code is case-insensitive
  • The extension name of C# file is .vbhtml

Example

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

Run Instance

More information about C# and Visual Basic

If you want to learn more about Razor and C# and Visual Basic programming languages, please visit the Razor Section.