User controls are made for reusability across ASP.NET pages, similar to master pages. Instead of sharing base page layout, user controls share group of HTML/ASP.NET built-in server controls or a specific form layout, e.g. comment submission or guest notes.
A user control can contain both HTML controls and ASP.NET server controls, including client-side scripts.
The user controls usually include Control
directive on top of its definition:
<%@ Control Language="C#" AutoEventWireup="True" CodeFile="UserControl.ascx.cs" %>
Like ASPX page, user controls consists of markups which can be associated with a code behind file to perform certain events and tasks, therefore all HTML tags available on ASPX page can be used on user controls except <html>
, <body>
and <form>
tags.
Here is an example for simple user control markup:
<%-- 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>
Code-behind example:
// UserControl.ascx.cs
public partial class UserControl : System.Web.UI.UserControl
{
protected void Button1_Click(Object sender, EventArgs e)
{
Label1.Text = "Hello World!";
}
}
Before a user control inserted in ASPX page, Register
directive should declared on top of the page referencing the user control with its source URL, tag name & tag prefix.
<%@ Register Src="UserControl.ascx" TagName="UserControl" TagPrefix="uc" %>
Afterwards, you can place user control inside ASPX page like ASP.NET built-in server control:
<uc:UserControl ID="UserControl1" runat="server" />