1、显示当前日期和时间
C# 示例
代码:@{var currentTime = DateTime.Now;}<p>当前时间是:@currentTime.ToString("yyyy年MM月dd日 HH:mm:ss")</p>
说明:使用 Razor 语法@{ ... }
来包含 C# 代码块。DateTime.Now
获取当前日期和时间,然后通过ToString
方法格式化为指定的字符串格式。
VB 示例
代码:@CodeDim currentTime As DateTime = DateTime.NowEnd Code<p>当前时间是:@currentTime.ToString("yyyy年MM月dd日 HH:mm:ss")</p>
说明:使用 Razor 语法@Code ... End Code
来包含 VB 代码块,声明并初始化一个DateTime
对象,然后将日期和时间格式化为指定的字符串格式。
2、使用循环显示数组中的元素
C# 示例
代码:@{string[] fruits = { "苹果", "香蕉", "橙子" };}<p>水果列表:@foreach (var fruit in fruits){@fruit }</p>
说明:定义一个字符串数组fruits
,使用foreach
循环遍历数组中的每个元素,并在 HTML 中输出每个元素。
VB 示例
代码:@CodeDim fruits() As String = {"苹果", "香蕉", "橙子"}End Code<p>水果列表:@For Each fruit In fruits@fruitNext</p>
说明:定义一个字符串数组fruits
,使用For Each
循环遍历数组中的每个元素,并在 HTML 中输出每个元素。
3、连接数据库并执行查询(以 SQL Server 为例)
C# 示例
代码:@using System.Data.SqlClient@{var connectionString = "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=YourDatabase;Integrated Security=True";var query = "SELECTFROM Customers";var customers = new List<string>();using (var connection = new SqlConnection(connectionString)){connection.Open();using (var command = new SqlCommand(query, connection)){using (var reader = command.ExecuteReader()){while (reader.Read()){customers.Add(reader["CustomerName"].ToString());}}}}<p>客户列表@foreach (var customer in customers){@customer }</p>
说明:使用System.Data.SqlClient
命名空间来连接 SQL Server 数据库,定义连接字符串和查询语句,使用SqlConnection
、SqlCommand
和SqlDataReader
对象执行查询,并将结果存储在customers
列表中,最后在 HTML 中输出客户列表。
VB 示例
代码:@Imports System.Data.SqlClient@CodeDim connectionString As String = "Data Source=(localdb)MSSQLLocalDB;Initial Catalog=YourDatabase;Integrated Security=True"Dim query As String = "SELECTFROM Customers"Dim customers As New List(Of String)()Using connection As New SqlConnection(connectionString)connection.Open()Using command As New SqlCommand(query, connection)Using reader As SqlDataReader = command.ExecuteReader()While reader.Read()customers.Add(reader("CustomerName").ToString())End WhileEnd UsingEnd UsingEnd UsingEnd Code<p>客户列表@For Each customer In customers@customerNext</p>
说明:使用Imports System.Data.SqlClient
导入命名空间,定义连接字符串和查询语句,使用SqlConnection
、SqlCommand
和SqlDataReader
对象执行查询,并将结果存储在customers
列表中,最后在 HTML 中输出客户列表。
1、问:如何在ASP.NET Web Pages中使用Razor语法?
答:在ASP.NET Web Pages中,Razor语法用于将服务器端代码嵌入到HTML页面中,对于C#,使用@{ ... }
来包含代码块;对于VB,使用@Code ... End Code
来包含代码块,在代码块中可以编写变量声明、逻辑控制、循环等代码,然后通过在代码块外部使用@变量名
的方式来在HTML中输出变量的值。
2、问:ASP.NET Web Pages与ASP.NET MVC有什么区别?
答:ASP.NET Web Pages是一种简化的编程模型,主要用于快速创建相对简单的网页,它将代码和标记混合在一起,类似于PHP等语言的开发方式,而ASP.NET MVC是一种更复杂的架构模式,它遵循模型 视图 控制器(MVC)的设计模式,将应用程序分为模型(数据和业务逻辑)、视图(用户界面)和控制器(处理用户输入和协调模型与视图)三个部分,各部分职责明确,更便于管理和维护大型的Web应用程序,并且提供了更好的可测试性和可扩展性。