Windows DevCenter    
 Published on Windows DevCenter (http://www.windowsdevcenter.com/)
 See this if you're having trouble printing code examples


What Are Web Parts?

by Jesse Liberty
01/10/2006

Today's web application is customizable in ways that could only have been dreamed of five years ago. One significant aspect of enhancing the user's ability to customize a site is the ability for the customer to decide what information is displayed on a page, and where that information is located. Many of the most popular web sites are beginning to allow this kind of customization by their users, from Yahoo to high-end news and financial services applications like Charles Schwab.

Let's take a quick look at the "MyYahoo" page, in which I am offered the following choices as shown in Figure 1:

You can create each of these options for your own users in a .NET 2005 application using Personalization, Web Parts, and Themes. This article will focus on Web Parts, and to see how they work, we'll build a simple application that allows the user to choose content and decide where it is placed.

Figure 1
Figure 1. My Yahoo customization

Begin by creating a new ASP.NET application named WebParts (or download the the complete project).

To get started, follow these steps:

  1. Open the Web Parts section of your Toolbox, and drag a Web Part Manager onto Default.asxp. (The job of the Web Part Manager is to track and coordinate all of the web part controls on the page. It will not be visible when the page is running.)
  2. Add a new table, with two rows and three columns. Rearrange the columns so that they are not of even size.
  3. Drag a Web Part Zone into each of the six table cells. In Design mode, click on each zone and re-size it to more or less fill the column. Your page should now look something like Figure 2:

Thumbnail, click for full-size image.
Figure 2. Web Parts Design view--click for full-size image.

Your source at this point should look like this:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
  <title>WebZones</title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
     <asyWebPartManager ID=yWebPartManager1" runat="server" />
     <table width="75%">
      <tr>
        <td  style="width:25%">
          <asp:WebPartZone ID="WebPartZone1" runat="server" Height="69px" Width="168px">
          </asp:WebPartZone>
        </td>
        <td style="width:50%">
          <asp:WebPartZone ID="WebPartZone2" runat="server" Height="80px" Width="344px">
          </asp:WebPartZone>
        </td>
        <td style="width:auto">
          <asp:WebPartZone ID="WebPartZone3" runat="server" Height="77px" Width="162px">
          </asp:WebPartZone>
        </td>
      </tr>
      <tr>
        <td>
          <asp:WebPartZone ID="WebPartZone4" runat="server" Height="57px" Width="166px">
          </asp:WebPartZone>
        </td>
        <td>
          <asp:WebPartZone ID="WebPartZone5" runat="server" Height="66px" Width="341px">
          </asp:WebPartZone>
        </td>
        <td>
          <asp:WebPartZone ID="WebPartZone6" runat="server" Height="64px" Width="165px">
          </asp:WebPartZone>
        </td>
      </tr>
     </table>
  </div>
  </form>
</body>
</html>

Click on each zone, and a smart tag opens, offering you the option to auto-format that Web Part Zone as shown in Figure 3.

Figure 3
Figure 3. Auto-formatting a Web Part Zone

Select, for example, Professional format, and then switch to Source mode. You'll note that many elements have been added to your Web Part Zone. You can now copy this modified Web Part Zone over the existing zones in the other columns to give your page a uniform look (don't forget to switch back to Design mode and re-size the larger zones).

Programming ASP.NET

Related Reading

Programming ASP.NET
Building Web Applications and Services with ASP.NET 2.0
By Jesse Liberty, Dan Hurwitz

Populating the Zones

This is a good time to put controls into some of the zones. Switch to Source mode, drag a Label into zone 1, and set the Title attribute to "Today's News" and the text (between the opening and closing label marks) to "Entire world declares peace!" Drag a List Box into zone 3, set the Title to "Favorite Books," and add the name of some of your favorite books to the List Box items collection.

Note that when you set the Title attribute, Visual Studio complains because neither the Label control nor the List Box control has a Title attribute. Yet, when you switch to Design view and when you run the application, there is the title properly displayed (as shown in Figure 4).

Figure 4
Figure 4. Title in Label

While Label does not have a Title attribute, all Web Parts do. When you drag any ASP.NET control into a Web Part Zone, it is wrapped in a Web Part, and thus has the Title, and also has the drop-down menu, as shown above in Figure 4.

Enabling Editing and Layout Changes

In order to allow your user to edit and change the layout, you must provide them with a way to change the display mode. You would think that this is so common a need that Microsoft would include a control to manage this, but, bizarrely, they do not. Instead the documentation tells you to create a user control, and provides example code. Follow these painless steps:

  1. Right-click on the application in Solution Explorer and choose Add New Item.
  2. In Templates, click on Web User Control, name the file DisplayModeMenu.ascx, and click the Add button.
  3. Copy the following code into the page, just below the header that was provided for you by Visual Studio.
    <asp:Panel ID="Panel1" runat="server" BackColor="lightgray" BorderWidth="1" Font-Names="Verdana, Arial, Sans Serif"
        Width=150">
        <asp:Label ID="Label1" runat="server" Font-Bold="true" Font-Size="8" Text=" Display Mode"
            Width="120"></asp:Label>
        <asp:DropDownList ID="ddlDisplayMode" runat="server" AutoPostBack="true"
            OnSelectedIndexChanged="ddlDisplayMode_SelectedIndexChanged" Width="120">
        </asp:DropDownList>
    </asp:Panel>

Right-click on the user control page and go to the code-behind page to put in the event handlers:

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 DisplayModeMenu : System.Web.UI.UserControl
{
   // Use a field to reference the current WebPartManager control.
   WebPartManager webPartManager;

   public void Page_Init( object sender, EventArgs e )
   {
    Page.InitComplete += new EventHandler( InitComplete );
   }

   // when the page is fully initialized
   public void InitComplete( object sender, System.EventArgs e )
   {
    webPartManager = WebPartManager.GetCurrentWebPartManager( Page );

    String browseModeName = WebPartManager.BrowseDisplayMode.Name;

    foreach ( WebPartDisplayMode mode in
    webPartManager.SupportedDisplayModes )
    {
     String modeName = mode.Name;
     if ( mode.IsEnabled( webPartManager ) )
     {
      ListItem listItem = new ListItem( modeName, modeName );
      ddlDisplayMode.Items.Add( listItem );
     }
    }
   }

   // Change the page to the selected display mode.
   public void ddlDisplayMode_SelectedIndexChanged( object sender,
   EventArgs e )
   {
    String selectedMode = ddlDisplayMode.SelectedValue;

    WebPartDisplayMode mode =
     webPartManager.SupportedDisplayModes[selectedMode];
    if ( mode != null )
    {
     webPartManager.DisplayMode = mode;
    }
   }

   // Set the selected item equal to the current display mode.
   public void Page_PreRender( object sender, EventArgs e )
   {
    ListItemCollection items = ddlDisplayMode.Items;
    int selectedIndex =
    items.IndexOf( items.FindByText( webPartManager.DisplayMode.Name ) );
    ddlDisplayMode.SelectedIndex = selectedIndex;
   }
}

Adding the User Control to Your Page: Drag and Drop

Return to Default.aspx in design mode, and make room between your Web Part Manager and your table of Web Part Zones. Drag the ascx file icon from Solution Explorer onto your page and <bang!> your control is registered and ready to use! (you can check the source code and see that the registration statement has been added for you).

Before running your program, delete a Web Part Zone from one of the cells and in its place drag in an Editor Zone from the Toolbox. Right-click on the smart tag and use the auto-format option to set the Professional format. Switch to Design view and find your Editor Zone, and drag in an Appearance Editor part:

<ZoneTemplate>
  <asp:AppearanceEditorPart ID="AppearanceEditorPart1" runat="server" />
    </ZoneTemplate>

Run the application. If you switch from Browse to Design mode, the empty Web Part Zones become visible, and you can drag a control from one zone to another, as shown in Figure 5.

Figure 5
Figure 5. Dragging a control in Design mode

When you return to Browse mode, the control is where you've placed it.

You'll notice that if you choose Edit mode, nothing appears to happen. While in Edit mode, however, click the arrow next to the title of your control, and you now have a new option, Edit, as shown in Figure 6.

Figure 6
Figure 6. Edit menu choice

Click Edit and the Editor Zone you created appears and allows you to edit the control as shown in Figure 7.

Figure 7
Figure 7. Editing a zone

Catalogs

One of the coolest features of Web Parts is that you can allow your users to pick and choose which controls they would like on their page, and where they'd like to put them. To see this at work, open Default.asxp in Source mode and find a Web Part Zone with no controls in it. Delete the Web Part Zone from the column and drag in a Catalog Zone. Switch to Design view and click on your new Catalog Zone and then click the smart tag to set the format to Professional.

Drag a Declarative Catalog Part into the Catalog Zone and click on its smart tag and choose Edit Templates. Next, drag a Calendar control into the Web Parts Template and use its smart tag to format it, and drag a File Upload control into the template. Then use the Declarative Catalog control's smart tag to stop editing the template. Notice that your two controls are marked "untitled." Switch to Source view, find the Calendar, and add the clever title "Calendar" as shown in this snippet:

  <ZoneTemplate>
    <asp:DeclarativeCatalogPart ID="DeclarativeCatalogPart1" runat="server">
      <WebPartsTemplate>
        <asp:Calendar> Title= "Calendar" ID="Calendar1" runat="server" BackColor="White" BorderColor="#999999"

Add a title to the File Upload control as well. Your Catalog Zone control should look more or less like Figure 8.

Figure 8
Figure 8. Catalog Zone -- two controls

Return to source code. Examine the Catalog Zone carefully and you'll see that there is a Zone Template element, within which is a Declarative Catalog Part, within which is a WebPartsTemplate, which in turn holds both the Calendar and the File Upload controls. Find the closing tag for the Declarative Catalog Part, and in between that closing tag and the tag that closes the Zone Template, drag a Page Catalog Part control. This latter control will list the Web Parts on the page and will allow the user to reopen Web Parts that were closed (amazingly, there is no other way for the user to do so!).

Run the application and choose Catalog from the Display Mode drop down. The Catalog Zone has an upper part and a lower part. The upper part tells you that the Declarative Catalog has two items and the Page Catalog has zero items. The lower portion displays the Declarative Catalog. Add a Calendar control to Web Part Zone 2 by checking Add A Calendar as shown in Figure 9.

Figure 9
Figure 9. Add a Catalog Part

When you click Add, the calendar appears in Web Part Zone 2 as the user hoped.

Showing Closed Controls

Click on Browse mode. You should have three controls showing (Today's News, Favorite Books, and Calendar). Click on the menus on each in turn: close Today's News and Favorite Books, and minimize the Calendar. While the menu on Calendar lets you restore it, Today's News and Favorite Books are gone!

To restore them, switch to Catalog mode and notice that the Page Catalog link now shows that there are two controls available. Click the link and select each control in turn and restore it (you can add it to whichever zone you'd like). Switch back to browse mode and the missing controls are back <whew!>.

Jesse Liberty is a senior program manager for Microsoft Silverlight where he is responsible for the creation of tutorials, videos and other content to facilitate the learning and use of Silverlight. Jesse is well known in the industry in part because of his many bestselling books, including O'Reilly Media's Programming .NET 3.5, Programming C# 3.0, Learning ASP.NET with AJAX and the soon to be published Programming Silverlight.


Return to the Windows DevCenter.

Copyright © 2009 O'Reilly Media, Inc.