Web Pages Razor
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 functionality of traditional ASP.NET markup, But easier to use and easier to learn
Razor is a server-side markup syntax, much like ASP and PHP
Razor supports C# and Visual Basic programming language
Add Razor code
Remember the web page in the example in the previous chapter:
<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 instance:
Instance
<!DOCTYPE html> <html> <body> <h1>Hello Web Pages</h1> <p>The time is @DateTime.Now</p> </body> </html>
Run instance»
Click the "Run instance" button to view the online instance
This page Contains normal HTML tags, in addition to adding an @-marked Razor code.
Razor code can complete a variety of 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 @{ ... } in
Inline expressions (variables and functions) begin with @
Code statements end with a semicolon
Variables are declared using the var keyword
Strings are enclosed in quotation marks
C# code is case-sensitive
C# The extension of the file is .cshtml
<html> <body> <!-- 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 + " Here in Huston it is: " + weekDay; } <p>The greeting is: @greetingMessage</p> </body> </html>
Run Example»Click the "Run Example" button to view the online example
Main Razor VB syntax rules
- Razor code blocks are enclosed in @Code ... End Code
- Inline expressions (variables and functions) begin with @
- Variables are declared using the Dim keyword
- Strings are enclosed in quotation marks
- VB code is not case-sensitive
- The extension of VB file is .vbhtml
<!-- 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 & " Here in Huston it is: " & weekDay End Code <p>The greeting is: @greetingMessage</p>
More about C# and Visual Basic
If If you want to learn more about Razor, C#, and Visual Basic programming languages, check out the Razor section of this tutorial.