Feb 10, 2010

Building ASP.NET UserControls

Introduction

If you are Classic ASP programmer or PHP programmer, you probably use SSI include files quite a lot on your web applications and you probably also know that this has worked quite reasonably well for all of you. But the major disadvantages would be maintaining the code once your web projects has grow bigger. Major problem would be to keep up with the HTML opening and closing tags. Its quite hard to debug the code if you are adding some HTML files in your include files and then later on you find that it produce funny result on certain page. There are no visual GUI or IDE that can help you to see the design view. The only way to debug is by viewing the page in the browser. This has taken quite a lot of developer time. The code was also very messy and also you might need to include all your include files in correct order and lots of developer normally will do copy and paste for all their page.

Luckily in ASP.NET technology, this problem has been solved with the introduction of UserControl. UserControl is basically use the same technology like the SSI includes except that it is a self contained objects where you can set the properties,attributes and methods. UserControl also can be designed using Visual Studio design view which allow you to see the layout of your page nicely.

Main

In this article, I will be presenting some simple example of my existing projects that use UserControls.
We will be doing some Header and Footer UserControls that expose some properties and attributes.
Now, let's start writing some code for creating UserControl.

Open Visual Studio 2005, Add New Web Site and Choose to add New UserControl. First one should be named as Header.ascx and second one as Footer.ascx.

If you look at the HTML source for the user control, you see several interesting differences from a standard ASP.NET Web Page
<%@ CONTROL LANGUAGE="C#" AUTOEVENTWIREUP="true" CODEFILE="Header.ascx.cs" I

INHERITS="UserControl_Header" %>
First,notice that the source uses @Control directive rather than @Page directive which a standard Web page would use. Second, notice that unlike a standard ASP.NET Web Page,no other HTML tags such as body,or DIV exists on the control. The web page containing the user control provides the basic HTML tags such as and
tags.In fact if you try to add server side form tags to the user control,ASP.NET will returns an error when the page is served to the clients.

Now, add this code into your Header.ascx
<%@ CONTROL LANGUAGE="C#" AUTOEVENTWIREUP="true" CODEFILE="Header.ascx.cs" INHERITS="Header" %>

<TABLE BORDER="0" WIDTH="100%">

   <TR>

       <TD>

           I am header User Control.TD>

       <TD>

           Today Date is <%=Date %>

       TD>

       <TD>

           Our Phone Number is <%=PhoneNumber %>

       TD>

   TR>

   <TR>

       <TD COLSPAN="3" BGCOLOR=<%=BgColor %>>

           <ASP:MENU ID="Menu1" RUNAT="server" ORIENTATION="Horizontal" WIDTH="100%" BACKCOLOR="#B5C7DE"

                DYNAMICHORIZONTALOFFSET="2" FONT-NAMES="Verdana" FONT-SIZE="0.8em" FORECOLOR="#284E98"

                STATICSUBMENUINDENT="10px">

               <ITEMS>

                   <ASP:MENUITEM TEXT="Home" VALUE="New Item">ASP:MENUITEM>

                   <ASP:MENUITEM TEXT="Our Products" VALUE="New Item">ASP:MENUITEM>

                   <ASP:MENUITEM TEXT="Our Features" VALUE="New Item">ASP:MENUITEM>

                   <ASP:MENUITEM TEXT="About Us" VALUE="New Item">ASP:MENUITEM>

                   <ASP:MENUITEM TEXT="Contact Us" VALUE="New Item">ASP:MENUITEM>

                   <ASP:MENUITEM TEXT="Why Choose Us" VALUE="New Item">ASP:MENUITEM>

               ITEMS>

               <STATICMENUITEMSTYLE HORIZONTALPADDING="5px" VERTICALPADDING="2px" />

               <DYNAMICHOVERSTYLE BACKCOLOR="#284E98" FORECOLOR="White" />

               <DYNAMICMENUSTYLE BACKCOLOR="#B5C7DE" />

               <STATICSELECTEDSTYLE BACKCOLOR="#507CD1" />

               <DYNAMICSELECTEDSTYLE BACKCOLOR="#507CD1" />

               <DYNAMICMENUITEMSTYLE HORIZONTALPADDING="5px" VERTICALPADDING="2px" />

               <STATICHOVERSTYLE BACKCOLOR="#284E98" FORECOLOR="White" />

           ASP:MENU>

       TD>

   TR>

TABLE>





From the code above, you notice that we use lots of server side tags <%=%> in the ascx file. The reason is because all that values is taken from the usercontrol properties and we can set the properties from the hosted user control page. The idea was be able to set and get the properties from the page.
In this example, we can set the background color of the user page, set the title and set the Date.

Now, add this code into Header.ascx.cs
using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;



public partial class Header : System.Web.UI.UserControl

{

   private string sTitle = "Welcome to My Company";

   private string sPhoneNumber = "12345667";

   private string sDate = "12/12/2007";

   private string sBgColor = "white";

   protected void Page_Load(object sender, EventArgs e)

   {



   }

   public string BgColor

   {

       get

       {

           return sBgColor;

       }

       set

       {

           sBgColor= value;

       }

   }

   public string Title

   {

       get

       {

           return sTitle;

       }

       set

       {

           sTitle = value;

       }

   }

   public string PhoneNumber

   {

       get

       {

           return sPhoneNumber;

       }

       set

       {

           sPhoneNumber = value;

       }

   }

   public string Date

   {

       get

       {

           return sDate;

       }

       set

       {

           sDate = value;

       }

   }



}
From the code above, you can see that we provide public get and set methods for all the properties that we use in Header.ascx file. We also provide default properties values for that incase if the UserControl does not override the property value.

Adding UserControl into Page

To add User Controls to the form, you can do it in two ways.
First, would be easy ways, but you need to have Visual Studio.
Open your Visual Studio in design View, and then drag the Header.ascx from SolutionExplorer into your Page. Once you do that, you can see that Visual Studio does all the necessary code for you.

Second way, would be manually code the UserControl in your page.
Add the Register directives as below
<%@ REGISTER src="Header.ascx" TAGNAME="Header" TAGPREFIX="uc1" %>
You can named the TagName and TagPrefix as you like. After that add the UserControl to the location you want on your page. The tag for user control should be like this
<UC1:HEADERS ID="Header1" RUNAT="server" TITLE="Hello Here" BGCOLOR="red"

PHONENUMBER="123455" />
Notice that in the UserControl above, we can define all the properties that we have previously provide public set methods.

You can also set and get the UserControl properties in code behind.
To get and set the UserControl properties, you can use code like this in your code behind
e.g Header1.Title = "Yes";
or Response.Write(Header1.Title);

UserControls is infact an object in your Page. You can add as many usercontrol on your page, or on multiple page. Each individual UserControl you add can have different set of properties and methods you can call.

Conclusion

ASP.NET UserControl is the new way of encapsulate all your code reuse in your web applications. Old way of doing this would be via SSI includes which can be very messy and very hard to maintain if your site grow. ASP.NET UserControl is infact the simplest form of ASP.NET control encapsulation. Because they are the simplest, they are also the easiest to create and use. Essentially user control is a grouping of existing server controls into a single container control. This enables you to group all your reusable part of webpage into UserControl. The basic example would be Login Controls, News Controls, Header Controls and etc.

If However you want to create your own controls from scratch that has the features like ASP.NET Web Server controls (Label,Button,TextBox), then you need to create the controls as Custom Controls. Custom controls is not discussed in this article.

No comments:

Post a Comment