Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

ASP.NET 网页 - 添加 Razor 代码


ASP.NET 网页使用 Razor 标记语言与 C# 或 VB 代码


Razor 标记语言

Razor 是一种简单的 **标记语法**,用于将服务器代码(C# 或 VB)嵌入到 ASP.NET 网页中。

示例

<!DOCTYPE html>

<html lang="en">
<head>
     <meta charset="utf-8" />
     <title>Web Pages 演示</title>
</head>
<body>
     <h1>Hello Web Pages</h1>
     <p>时间是 @DateTime.Now</p>
</body>
</html>
运行示例 »

上面的页面包含普通 HTML 标记和 Razor 标记。


C# 的 Razor 语法

  • C# 代码块用 @{ ... } 括起来
  • 内联表达式(变量或函数)以 @ 开头
  • 代码语句以分号结尾
  • 变量用 var 关键字或数据类型(int、string 等)声明
  • 字符串用引号括起来
  • C# 代码区分大小写
  • C# 文件扩展名为 .cshtml

C# 示例

<!-- 单语句块 -->
@{ var myMessage = "Hello World"; }

<!-- 内联表达式或变量 -->
<p>myMessage 的值为:@myMessage</p>

<!-- 多语句块 -->
@{
var greeting = "Welcome to our site!";
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + " Today is: " + weekDay;
}

<p>问候语为:@greetingMessage</p>
运行示例 »


VB 的 Razor 语法

  • VB 代码块用 @Code ... End Code 括起来
  • 内联表达式(变量或函数)以 @ 开头
  • 变量用 Dim 关键字声明
  • 字符串用引号括起来
  • VB 代码不区分大小写
  • VB 文件扩展名为 .vbhtml

VB 示例

<!-- 单语句块  --> 
@Code dim myMessage = "Hello World" End Code
 
<!-- 内联表达式或变量 --> 
<p>myMessage 的值为:@myMessage</p> 
 
<!-- 多语句块 --> 
@Code
dim greeting = "Welcome to our site!" 
dim weekDay = DateTime.Now.DayOfWeek 
dim greetingMessage = greeting & " Today is: " & weekDay
End Code


<p>问候语为:@greetingMessage</p>
运行示例 »

关于 C# 和 Visual Basic 的更多信息

如果您想了解更多关于 Razor 以及 C# 和 Visual Basic 编程语言的信息

请访问本教程的 Razor 部分


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.