Partilhar via


How to: Include a User Control in an ASP.NET Web Page

To use a user control, you include it in an ASP.NET Web page. When a request arrives for a page and that page contains a user control, the user control goes through all of the processing stages that any ASP.NET server control performs. For more information about these processing stages, see ASP.NET Page Life Cycle Overview.

To include a user control in a Web Forms page

  1. In the containing ASP.NET Web page, create an @ Register directive that includes:

    • A TagPrefix attribute, which associates a prefix with the user control. This prefix will be included in opening tag of the user control element.

    • A TagName attribute, which associates a name with the user control. This name will be included in the opening tag of the user control element.

    • A Src attribute, which defines the virtual path to the user control file that you are including.

      NoteNote

      The Src attribute value can be either a relative or an absolute path to the user control source file from your application's root directory. For flexibility, it is recommended you use a relative path. The tilde (~) character represents the root directory of the application. User controls cannot be located in the App_Code directory.

  2. In the body of the Web page, declare the user control element inside the form element.

  3. Optionally, if the user control exposes public properties, set the properties declaratively.

Example

The following example shows an ASP.NET Web page that contains a user control. The user control is in the file Spinner.ascx in the Controls folder. In the page, the control is registered to use the prefix uc and the tag name Spinner. The user control properties MinValue and MaxValue are set declaratively.

NoteNote

For details about the code for the user control used in this example, see How to: Create an ASP.NET User Control.

<%@ Page Language="VB" %>
<%@ Register TagPrefix="uc" TagName="Spinner" 
    Src="~\Controls\Spinner.ascx" %>
<html>
<body>
<form runat="server">
    <uc:Spinner id="Spinner1" 
        runat="server" 
        MinValue="1" 
        MaxValue="10" />
</form>
</body>
<%@ Page Language="C#" %>
<%@ Register TagPrefix="uc" TagName="Spinner" 
    Src="~\Controls\Spinner.ascx" %>
<html>
<body>
<form runat="server">
    <uc:Spinner id="Spinner1" 
        runat="server" 
        MinValue="1" 
        MaxValue="10" />
</form>
</body>

See Also

Tasks

How to: Create an ASP.NET User Control

Concepts

ASP.NET User Controls Overview