The ASP.NET 2.0 Web Parts Framework

An Introduction

LANGUAGES: C#

ASP.NET VERSIONS: 2.0

Almost any Web application that you create will need some kind of user customization. Fortunately, ASP.NET 2.0 makes this extremely easy to do by introducing the new Web Parts Framework. Web Parts in ASP.NET 2.0 are an integrated set of controls used for building Web sites that allow end users to modify the content, appearance, and behavior of Web pages directly from a browser. The neat feature about Web Parts is that you can accomplish all of this without having to write a single line of code.

 

This article will discuss the Web Parts Framework provided by ASP.NET 2.0 and how to utilize it to create personalized Web applications. Along the way, you ll also come to understand the different types of Web Parts supplied by the framework, and how to leverage them to create sophisticated ASP.NET applications.

 

Introduction

Web Parts are reusable pieces of code that allow you to logically group related functionality together into one unit. Once you add a Web Part to the ASP.NET page, they can then be shown, hidden, moved, and redesigned all by the user. Also by using Web Parts, you as a developer can empower your users with the ability to perform the following operations:

  • Personalize page content.
  • Personalize the page layout by allowing the users to drag Web Parts from one zone to another zone, or change its appearance, look and feel, and so on.
  • Users can also export and import Web Part controls so that the Web Parts can be effectively shared among other sites.
  • Users can create connections between two Web Parts by establishing connections between Web Part controls.

 

As a developer, you ll typically work with Web Parts in one of three ways: creating pages that use Web Part controls, creating individual Web Part controls, or creating complete personalizable Web portals. Now that you have an understanding of the features of Web Parts, let s discuss the different types of Web Parts. There are two kinds of Web Parts:

  • Custom. Custom Web Parts are those Web Part controls that derive from the System.Web.UI.WebParts.WebPart class.
  • Generic. A custom control that doesn t inherit from the WebPart class and is still used as a Web Part is called GenericWebPart. For example, if you place a TextBox control inside a WebPartZone (WebPartZone is a zone on the page that hosts the Web Part control) control, the TextBox control will be wrapped into a GenericWebPart class.

 

Any Web page that utilizes Web Parts will have one or more of the following controls:

  • WebPart. Renders the primary UI; most Web Parts UI controls fall into this category.
  • WebPartManager. Manages all Web Parts on a page. Each ASP.NET page can have only one WebPartManager control.
  • WebPartPageMenu. Creates a menu or dropdown list that enables users to change the display mode and personalization scope on a Web page. For example, the control can enable users to choose browse, design, edit, or catalog mode, and switch between user and shared personalization scope.
  • CatalogZone. Contains CatalogPart controls. Use this zone to create a catalog of Web Parts from which users can select controls to add to a page.
  • EditorZone. Contains EditorPart controls. Use this zone to enable users to edit and personalize Web Part controls on a page.
  • WebPartZone. Contains and provides overall layout for the WebPart controls that compose the main UI of a page. Use this zone whenever you create pages with Web Part controls. Pages can contain one or more zones.
  • ConnectionsZone. Contains Connection controls. This control is used to communicate from one Web Part to another.

 

When a Web Part is rendered by the WebPartZone, the zone will invoke some of the Web Part properties, such as Title, Description, Height, and Width. A key difference between a regular WebPart and a GenericWebPart is that when a GenericWebPart s Web Part-specific property is called, the GenericWebPart will look in the attributes collection of its ChildControl for an attribute of the same name as the property. This allows you to set certain Web Part properties on the generic control, even though the generic control doesn t contain these properties. For example:

 

 

  

    Description="Generic Web Part Control Description"

    ID="myControl1" Runat="server" />

 

 

This code will cause the Title property of the GenericWebPart (which is a Label control, in this case) to return the values specified in the above declaration. Now that you have an understanding of the different types of the Web Parts, as well as the controls that make up a Web Part, let s move on to discuss a generic Web Part example.

 

Creating a Generic Web Part

This section will discuss the implementation of a generic Web Part. To start, create a new Visual C# Web site named WebPartsDemo using Visual Studio 2005. Once the Web site is created, add to it a Web form named GenericWebPartExample.aspx. Figure 1 shows the code required for creating a generic Web Part.

 

<%@ Page Language="C#" %>

 Generic Web Part Example

 

Web Parts Demonstration Page

 


 

 

  

 

 

   

     headertext="Main">

     

     

       title="Generic Web Part">

       

This is an example of a generic web part

       wherein the contents of the web part are

       generated by a label control

      

     

   

  

Figure 1: Create a generic Web Part.

 

Let s examine the lines of code shown in Figure 1. To start with, you declare a WebPartManager control. The WebPartManager control is a must for any ASP.NET page that utilizes Web Parts. This control must be the first element in an ASP.NET Web form, above all other Web Parts, zones, or any other custom or specialized Web Part controls. The WebPartManager has no visual element associated with it; however, it is very crucial because of the required plumbing it provides for managing the interactions between Web Parts. Then the code declares a WebPartZone control, wherein it includes a Label control that consists of all the HTML elements that make up the display of the Web Part.

 

Figure 2 shows a screenshot of the output produced by the code shown in Figure 1, wherein you can choose to minimize or close the Web Part by clicking on the appropriate links.

 


Figure 2: The result of running the code from Figure 1.

 

Creating a Custom Web Part

To create a custom Web Part, you must first inherit from the WebPart class, then implement the RenderContents method. The following code gives you an idea of the skeleton implementation of a Web Part:

 

using System.Web.UI.WebControls.WebParts;

public class RegionWebPart : WebPart

{

 protected override void RenderContents(

  HtmlTextWriter writer)

 {

  //Add your implementation here

 }

}

 

Because a custom Web Part is nothing more than a custom control, you render the content of the control by overriding the RenderContents method. Let s start by creating a Web Part that displays the region information from the Region table in the Northwind database. The code required for implementing the Web Part is shown in Figure 3.

 

using System;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

using System.Web.UI;

using System.Web.UI.WebControls.WebParts;

namespace WebPartsDemo

{

 public class RegionWebPart : WebPart

 {

   public RegionWebPart()

   {

     this.Title = "Regions in the Northwind Database";

   }

   protected override void RenderContents(HtmlTextWriter writer)

   {

     string connectionString = ConfigurationSettings.

      ConnectionStrings["northwindConnection"].

       ConnectionString;

     //Retrieve Regions information

     DataTable regionTable = new DataTable();

     SqlDataAdapter adapter = new SqlDataAdapter

       ("Select * from Region", connectionString);

     adapter.Fill(regionTable);

     //Loop through all the rows in the DataTable

     foreach (DataRow row in regionTable.Rows)

     {

       //Display the row

       writer.Write(row["RegionID"] + " - " +

        row["RegionDescription"] + "
");     

     }

   }

 }

}

Figure 3: Create a Web Part that displays the region information from the Region table in the Northwind database.

 

The WebPart class has several members Title, Height, and Width that are used for configuring the title, height, and width of the Web Part. In the code example shown in Figure 3, you set the Title property of the Web Part to a specific value in the constructor. The RenderContents method is supplied with an HtmlTextWriter object as its argument, which allows you to write out the required contents using the Write method of the HtmlTextWriter object. Then the code retrieves the categories information from the categories table and writes them out to the user interface through the call to the Write method.

 

Now that you have an understanding of the Web Part implementation, let s discuss the Web form that will be used to host the Web Part. For the purposes of this example, let s add a new page named CustomWebPartExample.aspx to the WebPartsDemo Web site. Modify the code in the page to look as that shown in Figure 4.

 

<%@ Page Language="C#" %>

<%@ Register TagPrefix="customWebParts"

 Namespace="WebPartsDemo" %>

 Custom Web Part Example

 

Web Parts Demonstration Page

 

 

 

 

  

 

 

 

   

    headertext="Main">

    

     

      runat="server" title="Region Custom Web Part"/>

    

   

  

Figure 4: Modify the WebPartsDemo Web site.

 

The code shown in Figure 4 is very similar to the previous example shown in Figure 1, except that in this example the ZoneTemplate control (in the WebPartZone control) contains the custom Web Part created in the previous step. To accomplish this, you need to do two things: declare the register directive at the top of the page and import the namespace that contains the Web Part, then reference the control using the combination of the tag prefix and the class name of the custom control. Executing the code from Figure 4 results in the output shown in Figure 5.

 


Figure 5: The result of running the code from Figure 4.

 

Customizing the Layout of the User Interface

The previous example demonstrates the steps involved in creating and consuming a Web Part. In this example, you ll build on the previous example by adding the capability that allows the users to customize the layout of the user interface. To accomplish this, you need to add a WebPartPageMenu control, which is the topic of discussion in this section.

 

The WebPartPageMenu control is a key component that enables personalization. Adding this control to the page results in a dropdown menu being displayed that shows several options from which to choose. Let s add this control to the CustomWebPartExample.aspx page by adding the following lines of code right below the WebPartManager control declaration:

 

 Text="Display Mode" Mode="Menu">

 

 

 

This code will create a WebPartPageMenu control at the top of the page, allowing the users to change the layout by switching into design mode any time and then dragging and dropping Web Parts to any location they want. The neat thing about this feature is that, because the changes are persisted in a database, the changes made by the users are available even for their subsequent visits. Figure 6 shows the output produced by the page when displayed in a browser.

 


Figure 6: The Display Mode menu shows options for customizing the Web page.

 

Adding New Web Parts to the Page

One of the most interesting features of Web Parts is the support provided for customizing a Web page. This customization not only enables operations such as changing properties on existing Web Parts in the page, and minimizing and closing the Web Parts, but it also includes the ability to add completely new Web Parts to the page. To be able to allow the end users to add new Web Parts, you need to add the CatalogZone element to the page. Within the CatalogZone element, you can add any of the following catalog parts:

  • PageCatalogPart. This will display all the Web Parts in a page that have been previously closed in the page, thereby providing the end users with the ability to re-add them to the page, if required.
  • DeclarativeCatalogPart. This allows page developers to provide a pre-defined set of Web Parts from which the users can choose the desired Web Parts. These pre-defined Web Parts are declared in the DeclarativeCatalogPart element inside the CatalogZone element.
  • ImportCatalogPart. This allows end-users to import a .WebPart file that contains the definition of a Web Part and allows them to include it in their page.

 

Now that you ve had a look at the different types of catalog parts, let s look at an example Web form named CatalogPartExample.aspx to understand the implementation (see Figure 7).

 

<%@ Page Language="C#" %>

<%@ Register TagPrefix="customWebParts"

 Namespace="WebPartsDemo" %>

 Custom Web Part Example

 

Web Parts Demonstration Page

 

 

   Runat="server" Text="Display Mode" Mode="Menu">

   

   

 

 

 

 

 

        

 

 

 

 

 

 

   

    "server" headertext="Main">

     

       

         runat="server" title="Region Custom Web Part">

       

     

   

 

   

    "CatalogZone1" Runat="server">

     

       

         Runat="server" />

       

         ID="DeclarativeCatalogPart1" Runat="server">

        

           

             ID="CategoriesWebPart1" Runat="Server" />

         

       

     

   

 

   

     ID="btnChangeDisplayMode"

     OnClick="ChangeDisplayMode" />

 

 

Figure 7: An example Web form named CatalogPartExample.aspx.

 

Let s examine the code shown in Figure 7. The server-side code consists of a method named ChangeDisplayMode, which simply sets the DisplayMode property of the WebPartManager control to CatalogDisplayMode. This method is invoked when the Button control is clicked. After that, the code contains the usual WebPartManager and WebPartPageMenu controls, and a WebPartZone control that includes the Region Web part. One important difference from our previous code example is the addition of the CatalogZone control. The CatalogZone control contains PageCatalogPart and DeclarativeCatalogPart controls. The DeclarativeCatalogPart contains a Categories Web Part control that is very similar to the Region Web Part in terms of functionality. It simply displays the categories information from the Categories table in the Northwind database.

 

Navigate to the CatalogPartExample.aspx from the browser and you ll see the output shown in Figure 8.

 


Figure 8: Navigate to the CatalogPartExample.aspx from the browser to see this.

 

Click on the Customize Page link illustrated in Figure 8 and you ll be taken to the screen shown in Figure 9.

 


Figure 9: Click on the Customize Page link to get here.

 

The screenshot illustrated in Figure 9 displays the Catalog Zone, which displays the Page Catalog as well as the Declarative Catalog. The Page Catalog contains no Web Parts and the Declarative Catalog contains the Categories Web Part. If you click on the Declarative Catalog link shown in Figure 9, you ll see the screen illustrated in Figure 10.

 


Figure 10: Click the Declarative Catalog link from Figure 9 to get this screen.

 

The Declarative Catalog section shown in Figure 10 allows you to add the Categories Web Part to the page. Now check the Categories in the Northwind Database Web Part and click Add. This will result in the Categories Web Part being added to the Web page, which is shown in Figure 11.

 


Figure 11: Checking the Categories in the Northwind Database Web Part and clicking Add results in the Categories Web Part being added to the Web page.

 

Conclusion

This article provided a thorough discussion of the steps involved in creating and consuming Web Parts from an ASP.NET application. It also demonstrated the personalization support of the ASP.NET 2.0 Web Parts Framework through an example. Finally, it provided a detailed discussion of the steps involved in adding Web Parts to an ASP.NET page.

 

This article only touched on the basic concepts of Web Parts. Advanced features, such as creating personalizable user-defined properties, creating custom Web Part menus, communication between Web Parts, and so on, will be discussed in a later article.

 

The sample code in this article is available for download.

 

Thiru Thangarathinam works at Intel Corp. in Chandler, AZ. He specializes in architecting, designing, and developing distributed enterprise class applications using .NET-related technologies. He has co-authored a number of books in .NET-related technologies. He has also been a frequent contributor to leading technology-related online publications. He can be reached at mailto:[email protected].

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish