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 embedding server-based code into webpages.
- Razor has the functionality of traditional ASP.NET markup but is easier to use and learn.
- Razor is a server-side markup syntax similar to ASP and PHP.
- Razor supports C# and Visual Basic programming languages.
Adding Razor Code
Remember the webpage from the previous chapter's example:
Now, add some Razor code to the example:
Example @DateTime.Now
This page contains regular HTML markup, along with Razor code identified by the @ symbol.
Razor code performs all actions on the server in real-time and displays the results. (You can specify formatting options, otherwise, it will display the default.)
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
- The file extension for C# is .cshtml
C# Example
@{ var myMessage = "Hello World"; }
@myMessage
@{
var greeting = "Welcome to our site!";
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + " Today is: " + weekDay;
}
@greetingMessage
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
- The file extension for VB is .vbhtml
VB Example
@Code dim myMessage = "Hello World" End Code
@myMessage
@Code
dim greeting = "Welcome to our site!"
dim weekDay = DateTime.Now.DayOfWeek
dim greetingMessage = greeting & " Today is: " & weekDay
End Code
@greetingMessage
More About C# and Visual Basic
If you want to learn more about Razor, C#, and Visual Basic programming languages, please check out the Razor section of this tutorial.