戰地連結︰ Home My Flickr NBA.com About

2009年7月20日星期一

ASP.NET User Control - Part 1

Overview

User Control is quite useful in creating a customized control which can be reused throughout pages. Instead of creating a custom server control, developers can create user control which (in my opinion) is easier to create and modify the control layout.

In this part, I will talk about how to create a user control and include it in an .aspx page.

Reference

ASP.NET User Controls Overview

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

Steps

Create a User Control

Creating a user control is very simple with few steps:

  1. You need to have a Web Application Project
  2. In Solution Explorer, right-click on the project's name (or a folder), select "Add" => "New Item..."
  3. Select "Web User Control" under "Web" category, give the control a name and click "Add"
  4. Done!

The newly created user control consists of a .ascx (not .aspx) page and a code behind file (just ignore the designer file). The .ascx page currently contains nothing but a "@ Control" directive.

User control .ascx page is very much like a snippet of an .aspx page, you can modify the layout of the user control by adding HTML tags or ASP.NET controls in it just like what you do to .aspx page. Below is the code of a very simple .ascx page:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestUserControl.ascx.cs" Inherits="MyTestWeb.Web.Controls.TestUserControl" %>

 

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />

<asp:Button ID="BtnSubmit" runat="server" Text="Submit" />

 

Include a User Control in an .aspx page

After a User Control is created, it can be used by any .aspx page within the same Web Application by including the control into the page.

To Include a User Control, we have to do 2 things:

  1. Create a "@ Register" directive which specify the "TagPrefix", "TagName" and "Src" (Source file) of the User Control.
  2. Declare the User Control with tag "<TagPrefix:TagName   />" just like any other ASP.NET control (the difference is ASP.NET Control start with TagPrefix "asp")

Below shows the code of a simple .aspx page including the User Control we just created.

<%@ Page Language="C#" MasterPageFile="~/Pages/Global.Master" AutoEventWireup="true"

    CodeBehind="TestPageWithMaster.aspx.cs" Inherits="MyTestWeb.Web.Pages.TestPageWithMaster"

    Title="Untitled Page" %>

 

<%-- "@ Register" directive --%>

<%@ Register TagPrefix="uc" TagName="TestUserControl" Src="~/Controls/TestUserControl.ascx" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

    <form runat="server">

 

        <%-- User Control declaration --%>

        <uc:TestUserControl ID="TestUserControl1" runat="server" />

 

    </form>

</asp:Content>

沒有留言: