asp:feature
LANGUAGE: C#
ASP.NET VERSIONS:
2.0
Meet the Web Part Framework
Create Web apps easily with these powerful new ASP.NET
controls.
By Stephen Walther
Most Web sites display the exact
same content to everyone regardless of the needs and interests of the people
visiting them. For example, if both you and I surf to the home page of the New
York Times Web site, we'll both see exactly the same thing. This is true
even if the only reason that I visit the New York Times site is to see
the latest movie reviews and the only reason that you visit it is to see the
latest football scores. Wouldn't it be nice if both you and I could get exactly
what we want when we go to the same home page?
ASP.NET 2.0 includes a new set of
controls, called Web Parts, that are designed to address this very problem. Web
Parts are all about personalization. When a Web page is built using them,
anyone who views that page can modify its content and layout. If you have ever
personalized the MSN or Yahoo! home page, then you're already familiar with the
idea behind Web Parts (see Figure 1).
Figure1. You can personalize the MSN
home page so that it displays only the content that interests you.
Industry experts predict there will
be a healthy market for third-party custom Web Part controls. This bodes well
for you, given developers can potentially build new Web applications simply by
selecting controls out of a catalog of preexisting Web Parts. You'll have the
capabilities to build a Web application the same way you build a laptop computer
currently on http://www.dell.com - by
bundling preexisting components together.
In this article, I'll introduce you
to the ASP.NET 2.0 Web Parts Framework. You'll learn how to build a simple
company intranet portal and enable users to personalize the portal by taking
advantage of Web Parts. I'll walk you through creating the Northwind portal
page - an internal Web site used by the employees of the Northwind Traders Co.
- as an example.
Create Pages With
Web Parts
When designing a page with Web
Parts, you must start by defining the Web Parts it will contain. There are
three basic ways you can create a Web Part: You can use the ContentWebPart
Control, create a Web User Control, or create a Custom Control. The easiest way
is to use the ContentWebPart Control. You can wrap any type of content that you
please within a ContentWebPart template, then treat that content as a Web Part.
For example, this Web Part simply displays the static text "Hello World!":
<asp:ContentWebPart
id="HelloPart" runat="Server">
<ContentTemplate>
Hello World!
</ContentTemplate>
</asp:ContentWebPart>
Notice that the ContentWebPart is a
templated control. So, you place the text "Hello World" inside the
ContentTemplate template to display it. Also notice that we've provided our
ContentWebPart with an ID. Unlike many of the controls in ASP.NET 1.0, the
ContentWebPart requires a unique ID or you'll get an exception.
ContentWebParts are very easy to
create. However, they have some significant disadvantages. First, when you
create a Web Part with a ContentWebPart, you cannot use the same Web Part on
multiple pages (without doing a copy and paste of the code). Second, you cannot
easily add application logic to a ContentWebPart. A ContentWebPart is best
suited for displaying static text or the output of a simple control. (In fact,
because of these disadvantages, the ContentWebPart Control might not be
included in the final release of the ASP.NET 2.0 Framework.)
Normally, you'll create Web Parts
by creating Web User Controls. Web User Controls do not have the two
shortcomings I just mentioned. When you create a Web Part with a Web User
Control, you can reuse the same Web Part across multiple pages. Furthermore,
you can create very complicated Web Parts that contain significant application
logic. For example, you can create a Web Part that displays random quotations
by saving this code to a file named Quotes.ascx:
<%@ Control Language="C#"
%>
<Script runat="Server">
void Page_Load() {
ArrayList colQuotes = new ArrayList();
colQuotes.Add( "Early to bed, early to rise!" );
colQuotes.Add( "Look before you leap!" );
lblQuote.Text = (string)colQuotes
[ new Random().Next(2) ];
}
</Script>
<asp:Label id="lblQuote"
Runat="Server"/>
Notice that the Quotes Web Part is
nothing more than a standard Web User Control. The Web User Control randomly
displays one quotation from an ArrayList of quotations whenever it's loaded.
The final option for creating Web
Parts is to create a custom Web Control. This is appealing when you need to
hide the source code for your Web Part. For example, you might want to create a
Web Part that displays news headlines. (You could use a Web Service in your Web
Part to retrieve the latest news headlines from a central news server
periodically.) Furthermore, you might want to sell this control to companies so
they can display news headlines on their Web site home pages. In this case,
you'll want to hide the source code and create the Web Part by creating a custom
Web control. For example, you can use this code to create a custom Web Part
that displays the news item "Rain storm in Seattle!":
using System.Web.UI;
using System.Web.UI.WebControls;
public class NewsWebPart : WebPart {
protected override void RenderContents
(HtmlTextWriter writer) {
writer.Write( "Rain storm in Seattle!" );
}
}
Notice that you create a custom Web
Part by deriving from the base WebPart class. After you've derived your control
from the base WebPart class, you can build your control exactly the same way
you would create any other custom Web Control. In this case, we override the
RenderContents method to display the single news item.
Create Portal Web
Parts
To keep things simple, we'll create
three Web Parts for our Northwind intranet portal page. MotivationWebPart
displays different motivational messages at different times of the day,
ProductsWebPart displays a list of available products, and
EmployeeLookupWebPart contains a form that enables you to look up an employee's
phone extension when you provide the employee's last name.
We'll create all three Web Parts by
creating Web User Controls (files with an ASEX extension). Furthermore, we'll
take advantage of the sample data included with the Microsoft SQL Server
Northwind database, using it with our Web Parts.
We'll start by creating the
MotivationWebPart. This Web Part displays the time and different motivational
messages depending on the hour (see Figure 2):
<%@ Control Language="C#"
%>
<Script runat="Server">
void Page_Load() {
int hour = DateTime.Now.Hour;
lblMotivate.Text = DateTime.Now.ToString("t");
if (hour < 9)
lblMotivate.Text += " - Go back to sleep!";
else if (hour < 13)
lblMotivate.Text += " - Almost time for lunch!";
else if (hour < 17)
lblMotivate.Text += " - Almost time to go home!";
else
lblMotivate.Text += " - Go home!";
}
</Script>
<asp:Label id="lblMotivate"
Font-Name="Comic Sans MS"
Runat="Server" />
Figure 2. The Motivation Web Part
displays the time and a motivational message.
The ProductsWebPart is a little
more complicated. It displays a list of the 10 most expensive products the
Northwind Trading Co. sells (see Figure 3):
<%@ Control %>
<asp:GridView
id="MyGridView"
DataSourceId="Northwind"
HeaderStyle-BackColor="DeepSkyBlue"
AlternatingRowStyle-BackColor="PowderBlue"
runat="server" />
<asp:SqlDataSource
id="Northwind"
ConnectionString="server=localhost;uid=sa;pwd=secret;
database=Northwind"
SelectCommand="Select Top 10 ProductName, UnitPrice
FROM Products ORDER BY UnitPrice
DESC"
runat="server" />
Figure 3. The ProductsWebPart
displays the 10 most expensive products.
The ProductsWebPart is created from
two new controls in the ASP.NET 2.0 Framework; the GridView control is the
replacement for the ASP.NET 1.0 DataGrid control; and the SqlDataSource control
represents a connection to a data source. When the ProductsWebPart is
displayed, the SELECT statement contained in the SqlDataSource control's
SelectCommand property is executed and the results are displayed in the
GridView.
Our final Web Part enables someone
to look up an employee's phone extension based on the employee's last name (see
Figure 4):
<%@ Control %>
<asp:TextBox
id="txtLastName"
Text="Lookup Last Name"
runat="Server" />
<asp:Button
Text="Lookup"
runat="Server" />
<asp:DetailsView
DataSourceID="mySource"
AllowPaging="true"
EnableCaching="true"
CacheDuration="86400"
runat="Server" />
<asp:SqlDataSource
id="mySource"
ConnectionString="Server=localhost;UID=sa;PWD=secret;
Database=Northwind"
SelectCommand="SELECT LastName,FirstName,Extension
FROM Employees"
FilterExpression="LastName LIKE '@LastName%'"
runat="Server">
<FilterParameters>
<asp:ControlParameter Name="LastName"
ControlId="txtLastName"
PropertyName="Text" />
</FilterParameters>
</asp:SqlDataSource>
Figure 4. The EmployeeLookupWebPart
enables you to look up an employee's extension given his or her last name.
The EmployeeLookup Web Part takes
advantage of the new DetailsView control included with the ASP.NET 2.0
Framework. This control displays the contents of a single item from a data
source automatically. In this case, we're using the DetailsView control to
display the values of the LastName, FirstName, and Extension columns retrieved
from the data source when the user enters a last name in the TextBox control.
Notice the FilterExpression
property contained in the SqlDataSource control. This property enables you to
filter the results of the data returned from the SelectCommand. In this case,
we're filtering the results to return only the records that match the last name
the user enters into the TextBox control.
Divide a Page Into
Web Part Zones
Now that we've created the Web
Parts for our portal application, we're ready to add them to a Web page. When
you add Web Parts to a page, you add the Web Parts to something called a Web
Part Zone. A Web Part Zone is a region of a page that contains a collection of
Web Parts (see Figure 5).
<%-- Zone 1 --%>
<asp:WebPartZone id="Zone1" runat="Server">
<ZoneTemplate>
<custom:MotivationWebPart
id="MotivationPart" title="Motivation"
runat="Server" />
<custom:EmployeeLookupWebPart
id="EmployeeLookupPart" Title="Employee Lookup"
runat="Server" />
</ZoneTemplate>
</asp:WebPartZone>
<%-- Zone 2 --%>
<asp:WebPartZone id="Zone2" runat="Server">
<ZoneTemplate>
<custom:ProductsWebPart
id="ProductsPart" Title="Top Products"
runat="Server" />
</ZoneTemplate>
</asp:WebPartZone>
Figure
5. You can add two Web Part Zones to a page with the code in this page
fragment.
The first Web Part Zone - named
Zone1 - contains two of our Web Parts. It contains the MotivationWebPart and
the EmployeeLookupWebPart. The second Web Part Zone - named Zone 2 - contains a
single Web Part. It contains the ProductsWebPart (see Figure 6).
Figure 6. The Web Parts appear in
the two zones displayed by the Northwind Trading Co. intranet portal page in normal
display mode.
There is one other control you must
include in every page that contains Web Parts: The WebPartManager control.
Every page that contains Web Parts must contain one, and only one,
WebPartManager control. This control must appear before any Web Part Zones in a
page. The WebPartManager control is responsible for keeping track of the state
of all the Web Parts in a page. This control is important to us in the next
section.
Make Web Parts
Customizable
Thus far, you might be thinking
that Web Parts are not all that exciting. To this point, just about everything
that we've done with Web Parts, we could have done using normal user controls.
So why all the fuss?
In this section, you'll learn how
to unleash the true power of Web Parts by enabling users to personalize the
Northwind portal page. You'll also learn how to enable users to rearrange how
Web Parts are laid out on a page. And you'll learn how to enable users to add
new Web Parts from a catalog of Web Parts.
The secret to allowing both types
of personalization is the WebPartManager control. The WebPartManager control
has an important property that affects the behavior of all the Web Parts in a
page: the DisplayMode property. This property has four possible values. Catalog displays a catalog of available
Web Parts and enables users to rearrange the Web Parts on a page; Design enables users to rearrange the
Web Parts on a page; Edit enables
users to edit the properties of individual Web parts; and Normal displays the Web Parts without enabling users to edit or
rearrange the Web Parts on a page (the default mode).
If you want to do anything
interesting with Web Parts, then you need to change the WebPartManager
control's DisplayMode property.
The downloadable code for this
article contains the complete code for our Northwind Portal page (see the
Download box accompanying this article). Our Northwind portal page contains an
HTML table that divides the page into three columns. The first two columns
contain the two Web Part Zones that I discussed in the previous section. The
third column contains a new control named the CatalogZone control. It enables
you to display a catalog of Web Parts that a user can add to a page. For
example, after a user closes a Web Part, the user can add it back to the page
from the CatalogZone.
The Northwind Portal page also
contains a LinkButton control that's labeled Personalize. When a user clicks
the Personalize link, the PersonalizePage event handler is executed and the
page mode is changed to Catalog mode. In Catalog mode, the user can personalize
the page (see Figure 7). When the user is satisfied with the appearance of the
page, he can click End Personalize and the page reverts back to its normal
display mode.
Figure 7. In the Northwind Trading
Co. intranet portal page in Catalog display mode, the user is dragging the
EmployeeLookupWebPart from Zone 1 to Zone 2.
In the current version of the Web
Parts Framework, any personalization an anonymous user performs is saved in
view state. This means that any changes he makes will be lost when the
anonymous user leaves the page. (This behavior might change before the final
release of the Framework.)
On the other hand, if the user is
an authenticated user (for example, he was authenticated by using Forms
Authentication), then any changes he makes will be persisted. This means that
if an authenticated user makes changes to the content and layout of a page
using Web Parts, the changes will remain when he returns to the application.
There are many exciting features of
the Web Parts Framework that I was unable to cover in this brief article. For
example, the Framework includes several controls that enable users to edit Web
Parts properties. It also includes support for exporting a Web Part from one
page and importing it to another page.
The sample code in this article is
available for download.
Stephen Walther wrote the
best-selling book on ASP.NET, ASP.NET Unleashed. He was also the architect and lead developer
of the ASP.NET Community Starter Kit, a sample ASP.NET application produced by
Microsoft. He has provided ASP.NET training to companies across the United
States, including NASA and Microsoft, through his company Superexpert (http://www.AspWorkshops.com).