本文简要概述了 ASP.NET 中的内联代码和代码隐藏模型。
原始产品版本: ASP.NET
原始 KB 数: 303247
总结
本文介绍Microsoft .NET Framework 类库命名空间 System.Web.UI。
ASP.NET 支持两种创作页面的方法:
- 内联代码
- 代码隐藏
内联代码
内联代码是直接嵌入在 ASP.NET 页中的代码。 以下代码表示包含内联代码的示例 ASP.NET 页:
Myinlinecode.aspx
<%@ Language=C# %>
<HTML>
<script runat="server" language="C#">
void MyButton_OnClick(Object sender, EventArgs e)
{
MyLabel.Text = MyTextbox.Text.ToString();
}
</script>
<body>
<form id="MyForm" runat="server">
<asp:textbox id="MyTextbox" text="Hello World" runat="server"></asp:textbox>
<asp:button id="MyButton" text="Echo Input" OnClick="MyButton_OnClick" runat="server"></asp:button>
<asp:label id="MyLabel" runat="server"></asp:label>
</form>
</body>
</HTML>
代码隐藏
代码隐藏是指包含在单独类文件中的 ASP.NET 页的代码。 这允许将 HTML 与演示文稿逻辑完全分离。 以下示例演示了 ASP.NET 代码隐藏页:
MyCodebehind.aspx
<%@ Language="C#" Inherits="MyStuff.MyClass" %> <HTML> <body> <form id="MyForm" runat="server"> <asp:textbox id="MyTextBox" text="Hello World" runat="server"></asp:textbox> <asp:button id="MyButton" text="Echo Input" Onclick="MyButton_Click" runat="server"></asp:button> <asp:label id="MyLabel" runat="server" /> </form> </body> </HTML>Mycodebehind.cs
using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace MyStuff { public class MyClass : Page { protected System.Web.UI.WebControls.Label MyLabel; protected System.Web.UI.WebControls.Button MyButton; protected System.Web.UI.WebControls.TextBox MyTextBox; public void MyButton_Click(Object sender, EventArgs e) { MyLabel.Text = MyTextBox.Text.ToString(); } } }
在前面的示例中,可以使用以下语法来编译 Mycodebehind.cs:
csc.exe /out:mycodebehind.dll /t:library mycodebehind.cs
使用以下代码时,代码隐藏页继承自 Page 类。 Page 类位于 System.Web.UI namespace:
public class MyClass : Page
从 Page 类继承可让代码隐藏页访问 ASP.NET 内部对象,例如 Request 和 Response。 此外,从 Page 类继承提供了一个框架,用于处理 ASP.NET 页中控件的事件。
在前面的示例中,代码隐藏页是在运行 ASP.NET 之前编译的。 或者,可以使用标记引用代码隐藏类 SRC ,如下所示:
<%@ Language="C#" Inherits="MyStuff.MyClass" src="MyCodebehind.cs" %>
在这种情况下,ASP.NET 实时编译代码隐藏页。 仅当代码隐藏文件更新(通过时间戳更改检测到)时,才会执行此编译步骤。
Visual Studio .NET 中的代码隐藏支持
使用 Visual Studio .NET 创建 ASP.NET Web 窗体时,代码隐藏页是默认方法。 此外,生成解决方案时,Visual Studio .NET 会自动为你执行预编译。
注意
在 Visual Studio .NET 中创建的代码隐藏页包括一个特殊 page 属性, Code-behindVisual Studio .NET 使用该属性。