用户控件介绍

用户控件是为了跨 ASP.NET 页面的可重用性,类似于母版页。用户控件不是共享基页面布局,而是共享 HTML / ASP.NET 内置服务器控件组或特定表单布局,例如评论提交或客户注释。

用户控件可以包含 HTML 控件和 ASP.NET 服务器控件,包括客户端脚本。

用户控件通常在其定义之上包含 Control 指令:

<%@ Control Language="C#" AutoEventWireup="True" CodeFile="UserControl.ascx.cs" %>

与 ASPX 页面一样,用户控件由标记组成,这些标记可以与文件后面的代码相关联以执行某些事件和任务,因此 ASPX 页面上可用的所有 HTML 标签都可以用于除 <html><body><form> 标签之外的用户控件。

以下是简单用户控件标记的示例:

<%-- UserControl.ascx --%>
<%@ Control Language="C#" AutoEventWireup="True" CodeFile="UserControl.ascx.cs" %>
<div>
    <asp:Label ID="Label1" runat="server" />
    <br />
    <asp:Button ID="Button1" runat="server" Text="Click Here" OnClick="Button1_Click" />
</div>

代码隐藏示例:

// UserControl.ascx.cs
public partial class UserControl : System.Web.UI.UserControl
{
    protected void Button1_Click(Object sender, EventArgs e)
    {
        Label1.Text = "Hello World!";
    }
}

在用户控件插入 ASPX 页面之前,Register 指令应在引用用户控件的页面顶部声明,其源 URL,标记名称和标记前缀。

<%@ Register Src="UserControl.ascx" TagName="UserControl" TagPrefix="uc" %>

之后,你可以将用户控件放在 ASPX 页面中,如 ASP.NET 内置服务器控件:

<uc:UserControl ID="UserControl1" runat="server" />