ASP.NET Web Pages
- Add Razor code
In the following, you'll learn what is
R
azor? H
ow do I add Razor code?
What are the syntax rules for Razor C# and VB?
In this tutorial, we'll use the Razor tags of the code for C# and Visual Basic.
What is Razor?
-
Razor is a tag syntax that adds server-based code to a Web page
-
Razor has the ASP.NET tagging, but is easier to use and learn
-
Razor is a server-side tag syntax that looks like ASP and PHP
-
Razor supports the programming languages of C# and Visual Basic
Add Razor code
Remember the page in the example in the last chapter:
<!DOCTYPE html>
<html >
<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:
<!DOCTYPE html>
<html >
<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 an instance . . .
In addition to the normal HTML tags included in the page, a Razor code for the identity has been added.
Razor code is able to perform multiple actions in real time on the server and display the results. (
You can specify the formatting option, otherwise only the default items will be displayed.)
)
The main Razor C# syntax rule
-
The Razor code block is included in the . .
-
Inline expressions (variables and functions) begin with
-
The code statement ends with a sign
-
Variables are declared using the var keyword
-
Strings are enclosed in quotation marks
-
The case-sensitive code for C# is not the case
-
The extension of the C# file is .cshtml
An instance of C#
<!-- 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 an instance . . .
The main Razor VB syntax rule
-
Razor code blocks are included in the @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 case insenso sensitive
-
The extension of the 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 & " Today is: " & weekDay
End Code
<p>The greeting is:
@greetingMessage
</p>
Run an instance . . .
More about C# and Visual Basic
If you'd like to learn more about Razor, C#, visual Basic programming languages, check out the
Razor section of this tutorial.
Related tutorials
The C#tutorial