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 power of traditional ASP.NET markup, but is easier to learn, and easier to use
- Razor is a server side markup syntax much like ASP and PHP
- Razor supports C# and Visual Basic programming languages
Adding Razor Code
Remember the web page from 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 example »
The page contains ordinary HTML markup, with one addition: the @ marked Razor code.
The Razor code does all the work of determining the current time on the server and display it. (You can specify formatting options, or just display the default)
Main Razor Syntax Rules for C#
- Razor code blocks are enclosed in @{ ... }
- Inline expressions (variables and 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 »
Main Razor Syntax Rules for VB
- Razor code blocks are enclosed in @Code ... End Code
- Inline expressions (variables and 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
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.