ASP.NET Web Pages - Adding Razor Code
In this tutorial, we will use Razor markup with C# and Visual Basic code.
What is Razor?
- Razor is a markup syntax for adding server-based code to web pages
- Razor has the features of traditional ASP.NET markup, but is easier to use and easier to learn
- Razor is a server-side markup syntax, very similar to ASP and PHP
- Razor supports the C# and Visual Basic programming languages
Adding Razor Code
Remember the web page from the previous chapter's example:
Hello Web Pages
Now add some Razor code to the example:
Example
Hello Web Pages
The time is
@DateTime.Now
Run Example »
The page contains ordinary HTML markup, and in addition, an @-marked Razor code has been added.
Razor code can perform all actions on the server in real time and display the results. (You can specify formatting options; otherwise only the default items are displayed.)
Main Razor C# Syntax Rules
- Razor code blocks are enclosed in @{ ... }
- Inline expressions (variables and functions) start with @
- Code statements end with a semicolon
- Variables are declared using the var keyword
- Strings are enclosed in quotes
- C# code is case-sensitive
- C# files have the .cshtml extension
C# Example
@{ var myMessage = "Hello World"; }
The value of myMessage is:
@myMessage
@{
var greeting = "Welcome to our site!";
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + " Today is: " + weekDay;
}
The greeting is:
@greetingMessage
Run Example »
Main Razor VB Syntax Rules
- Razor code blocks are enclosed in @Code ... End Code
- Inline expressions (variables and functions) start with @
- Variables are declared using the Dim keyword
- Strings are enclosed in quotes
- VB code is not case-sensitive
- VB files have the .vbhtml extension
Example
@Code dim myMessage = "Hello World" End Code
The value of myMessage is:
@myMessage
@Code
dim greeting = "Welcome to our site!"
dim weekDay = DateTime.Now.DayOfWeek
dim greetingMessage = greeting & " Today is: " & weekDay
End Code
The greeting is:
@greetingMessage
Run Example »
More About C# and Visual Basic
If you want to learn more about the Razor, C#, and Visual Basic programming languages, please see the Razor section。