
在传统的 ASP.NET 项目中,aspx 页面输出内容有两种组织代码的方式:代码不分离(内联代码)和代码分离(CodeBehind),下面用简单的两个完整示例演示:
1、代码不分离(内联代码)
这种方式只有一个 .aspx 文件:
<%@ Page Language="C#" %>
<!DOCTYPE html>
<html>
<head>
<title>Hello World - 内联代码</title>
</head>
<body>
<%
// 直接在页面中输出字符串
Response.Write("hello, world.");
%>
<!-- 或者使用简写形式:<%="hello, world."%> -->
</body>
</html>2、代码分离(CodeBehind)
这种方式有一个 .aspx 文件和一个 .aspx.cs 文件,通过 Inherits 和 CodeBehind 指令关联:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="HelloWorld_CodeBehind.aspx.cs"
Inherits="HelloWorld_CodeBehind" %>
<!DOCTYPE html>
<html>
<head>
<title>Hello World - 代码分离</title>
</head>
<body>
<form id="form1" runat="server">
<!-- 用 Label 控件展示后台赋的值 -->
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</form>
</body>
</html>using System;
public partial class HelloWorld_CodeBehind : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// 在页面加载时为 Label 赋值
lblMessage.Text = "hello, world.";
}
}除此之外,还有一种称为服务器端脚本块的写法,像是上面两种的合体,也是只有一个 .aspx 文件:
<%@ Page Language="C#" AutoEventWireup="true" %>
<!DOCTYPE html>
<html>
<head>
<title>Hello World - 服务器端脚本块</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</form>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
lblMessage.Text = "hello, world.";
}
</script>
</body>
</html>
评论(0)
暂无评论。