master pages and navigation

33
5 Master Pages and Navigation T H E L O O K A N D F E E L O F A S I T E can be its savior or its downfall, and there are plenty of books and Web sites that instruct in design and us- ability. This chapter discusses not site design but how ASP.NET 2.0 aids in the design and consistency of sites. From the development perspective, generating a site that is consistent isn’t so hard, and there are plenty of ways it can be achieved. However, these are all custom solutions, not part of the underlying .NET Framework. ASP.NET 2.0 brings a solution that not only improves ways of providing UI reuse but also aids in maintenance of the site. Likewise, providing navigation within a site can be achieved easily, but you nearly always have to write code or buy a custom solution. ASP.NET 2.0 has a new framework that provides a simple and extensible solution for providing navigation. Master Pages in Detail In Chapter 1 we had a brief look at the idea of master pages, showing how they provide a template for all content pages. This provides a way to cre- ate a consistent look for a site, since the look is defined in the master page. Let’s refresh ourselves about how this works. Figure 5.1 shows an example of two content pages using a master page. The master page defines the page layout—that is, the shared UI and code plus any default content. In this case it is the light shaded content at the 141 05ASP.qxd 9/5/03 9:54 AM Page 141

Upload: alfredo-cancino

Post on 19-May-2015

653 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: Master Pages And Navigation

5Master Pages and Navigation

TH E L O O K A N D F E E L O F A S I T E can be its savior or its downfall, andthere are plenty of books and Web sites that instruct in design and us-

ability. This chapter discusses not site design but how ASP.NET 2.0 aids inthe design and consistency of sites. From the development perspective,generating a site that is consistent isn’t so hard, and there are plenty ofways it can be achieved. However, these are all custom solutions, not partof the underlying .NET Framework. A S P.NET 2.0 brings a solution that notonly improves ways of providing UI reuse but also aids in maintenance ofthe site.

Likewise, providing navigation within a site can be achieved easily, butyou nearly always have to write code or buy a custom solution. ASP.NET2.0 has a new framework that provides a simple and extensible solution forproviding navigation.

Master Pages in DetailIn Chapter 1 we had a brief look at the idea of master pages, showing howthey provide a template for all content pages. This provides a way to cre-ate a consistent look for a site, since the look is defined in the master page.Let’s refresh ourselves about how this works.

F i g u re 5.1 shows an example of two content pages using a master page.The master page defines the page layout—that is, the shared UI and codeplus any default content. In this case it is the light shaded content at the

141

05ASP.qxd 9/5/03 9:54 AM Page 141

Page 2: Master Pages And Navigation

top and left, re p resenting menus and other navigation features. The mas-ter page defines content areas using the C o n t e n t P l a c e H o l d e r c o n t rol, andit is into these areas that content pages place their content (shown as darkshaded areas in the figure). Pages that use a master page to define the lay-out can place content only in the areas defined by the C o n t e n t P l a c eHolder, thus enabling a consistent site design.

Creating Master PagesIn Visual Studio .NET “Whidbey”, creating master pages is simply a mat-ter of selecting Master Page from the Add New Item dialog. The newly createdmaster page is just an A S P.NET page with a diff e rent file extension (.master), so it fits with your existing knowledge. You don’t have to learnany new techniques, apart from the use of the C o n t e n t P l a c e H o l d e r c o n-t rol. Listing 5.1, for example, shows the contents of a master page newlyadded to a site.

M ASTER PA G E S AND NAV I G AT I O N142

Figure 5.1. Master pages in action

05ASP.qxd 9/5/03 9:54 AM Page 142

Page 3: Master Pages And Navigation

Listing 5.1. A Simple Master Page

<%@ Master language="VB" %>

<script runat="server">

</script>

<html><head runat="server">

<title>Untitled Page</title></head>

<body><form runat="server"><asp:ContentPlaceHolder

id="ContentPlaceHolder1" runat="server"></asp:ContentPlaceHolder>

</form></body></html>

You can see that this looks similar to existing ASP.NET pages and con-tains simple HTML and A S P.NET controls. The main diff e rence betweenthis page and a standard ASP.NET page is the use of the Master directiveand the file suffix . m a s t e r. The critical point is the use of the C o n t e n tP l a c e H o l d e r c o n t rol, which dictates where content pages can insert con-tent. The i d attribute uniquely identifies the placeholder, allowing morethan one placeholder to be in a master page. The master page can havecode as well as content, allowing the master page to be dynamic.

Turning this empty master page into one that defines the look and feelof a site is simply a matter of adding controls to get the required look. Fig-u re 5.2, for example, shows the addition of a table to define the page lay-out, with an area at the top where the logo and site description sit and a

THE GRIDVIEW CONTROL 143

Figure 5.2. The master page in design view

05ASP.qxd 9/5/03 9:54 AM Page 143

Page 4: Master Pages And Navigation

region down the left for the menu. In the middle we have the C o n t e n tPlaceHolder, which is the area we are leaving for content pages to fill in.

Using a Master PageTo create a page that uses the master page, you pick Content Pa g e f rom the A d d

New Item dialog, at which point you get the opportunity to pick which mas-ter page you wish the content page to inherit from, as shown in Figure 5.3.

When first created, the content page contains a single line of code:

<%@ Page language="VB" master="~/mysite.master" %>

Figure 5.4 shows this content page in design view. Notice how the contentd e fined in the master is grayed out and disabled—the only area allowedfor editing is that defined by the Content control.

The confusing thing here is that this C o n t e n t c o n t rol doesn’t seem toexist in the file—remember there was only a single line, the Page directive.

M ASTER PA G E S AND NAV I G AT I O N144

Figure 5.3. Picking a master page for a content page

Figure 5.4. A content page with an attached master

05ASP.qxd 9/5/03 9:54 AM Page 144

Page 5: Master Pages And Navigation

This is because at design time the content of the master page is re n d e re d ,but our page defines no content, so an empty region is displayed so the De-signer can prompt you where to add the C o n t e n t c o n t rol. This can be doneeither by selecting the C reate Empty Content option from the Common Ta s k s

menu or by simply dragging controls from the Toolbox into this re g i o n .Listing 5.2 shows the source view for a content page with a couple of

controls added.

Listing 5.2. Using a Master Page (MyPage.aspx)

<%@ Page Language="VB" Master="MySite.master" %>

<asp:Content id="Content1" ContentPlaceHolderId="ContentPlaceHolder1"runat="server">

<asp:Button id="Button1" runat="server" text="Button" /><asp:ListBox id="ListBox1" runat="server"></asp:ListBox"

</asp:Content>

The local content is within the Content control—content in a page thathas a master page cannot be outside a C o n t e n t c o n t rol. This ensures thatall content pages using a master have a consistent look. Since master pagescan contain multiple content areas, the i d of the C o n t e n t P l a c e H o l d e rc o n t rol is used to link the C o n t e n t c o n t rol to the C o n t e n t P l a c e H o l d e rc o n t rol in the master page. When the page is constructed, A S P.NET fir s tadds all of the content from the master page. Then it loops through theContentPlaceHolder controls and, for each, looks in the content page fora C o n t e n t c o n t rol where the C o n t e n t P l a c e H o l d e r I d matches the i d o fthe C o n t e n t P l a c e H o l d e r. This ensures that the correct content is placed inthe correct holder.

Default ContentAlong with layout and code that applies to all pages, the master page canalso supply default content, which can be overridden by content pages ordisplayed if not overridden. This is achieved by simply inserting the contentwithin the C o n t e n t P l a c e H o l d e r element. For example, our M y S i t e . m a s t e rpage could have the following default content:

<asp:ContentPlaceHolderid="ContentPlaceHolder1" runat="server">

<h2>Welcome</h2>Welcome to my site, where you'll findlots of interesting stuff.

</asp:ContentPlaceHolder>

M ASTER PA G ES IN DETA I L 145

05ASP.qxd 9/5/03 9:54 AM Page 145

Page 6: Master Pages And Navigation

Creating a new content file based on this master would give us the follow-ing line of code:

<%@ Page Language="VB" master="~/MySite.master" %>

Since we haven’t specified a C o n t e n t c o n t rol, all content is provided by themaster page, as shown in Figure 5.5.

Nested Master PagesMaster pages aren’t limited to a single master and content pages; the ar-chitecture allows for nested master pages, where a master page can have amaster page. This is particularly useful for sites that re q u i re some overallbranding and look but that also have subsites whose look must be consis-tent. For example, consider a corporation with group intranets—perh a p sone for the sales department and one for research. The company wishes tohave an overall look, including menus between the subsites, but allows thedepartments to design their parts of the site to fit their business needs. Inthis situation you could have three master pages—the top-level masterd e fining the corporate site image, a submaster for the sales department,and a submaster for the research department. The sales and research sub-master pages would define the corporate master as their master page. Theinheritance rules of master pages mean that any pages using one of thesubmaster pages receives content from all master pages in the hierarc h y(see Figure 5.6).

Notice that you can inherit from any level of the hierarchy—you aren’tlimited to using the bottom level. This allows you to provide generic con-tent pages that apply to the whole site, as well as pages that apply to indi-vidual site areas. Let’s take a look at the code that makes this possible,starting with the site master as shown in Listing 5.3.

M ASTER PA G E S AND NAV I G AT I O N146

Figure 5.5. A content page with no content other than default content

05ASP.qxd 9/5/03 9:54 AM Page 146

Page 7: Master Pages And Navigation

Listing 5.3. The Site Master Page (BigCorp.master)

<%@ Master %>

<html><head>

<link rel="stylesheet" type="text/css" href="MySite.css"></head>

<body><form runat="server">

<table width="100%" border="0"><tr>

<td><asp:Hyperlink ImageUrl="home.gif" runat="server"

NavigateUrl="BigCorp_Default.aspx" /></td><td>

<h1>Big Corp Intranet</h1></td><td>

<a href="BigCorp_SalesDefault.aspx">Sales</a>

M ASTER PA G ES IN DETA I L 147

Figure 5.6. Using nested master pages

continues

05ASP.qxd 9/5/03 9:54 AM Page 147

Page 8: Master Pages And Navigation

</td><td><a href="BigCorp_ResearchDefault.aspx">Research</a>

</td></tr>

</table><asp:ContentPlaceHolder runat="server"

id="MainContentRegion">Welcome to Big Corp. Please use the menus aboveto select the required department.

</asp:ContentPlaceHolder></form></body></html>

This simple master page, containing some content and a placeholder, isshown in design view in Figure 5.7. Now consider Listing 5.4, which shows a submaster page that inheritsfrom the first master page.

Listing 5.4. A Submaster Page (BigCorp_Sales.master)

<%@ Master Master="BigCorp.master"%>

<asp:Content ContentPlaceHolderId="MainContentRegion"runat="server">

<table border="0" width="100%"><tr>

<td><h2>Big Corp Sales</h2>

</td></tr><tr>

<td><table border="0" width="100%"><tr>

<td><a href="sales/page1.aspx" Menu 1</a></td><td><a href="sales/page2.aspx" Menu 2</a></td><td><a href="sales/page3.aspx" Menu 3</a></td><td><a href="sales/page4.aspx" Menu 4</a></td>

M ASTER PA G E S AND NAV I G AT I O N148

Figure 5.7. The site-wide master page (BigCorp.master)

05ASP.qxd 9/5/03 9:54 AM Page 148

Page 9: Master Pages And Navigation

M ASTER PA G ES IN DETA I L 149

Figure 5.8. The nested sales master page (BigCorp_Sales.master)

</tr></table>

</td></tr><tr><td>

<asp:ContentPlaceHolder runat="server"id="SalesContentRegion" />

</td></tr>

</table></asp:Content>

Because this page inherits from a master page, all content must bewithin a C o n t e n t c o n t rol, with a C o n t e n t P l a c e H o l d e r I d matching that ofthe master C o n t e n t P l a c e H o l d e r. However, we can also include C o n t e n tP l a c e H o l d e r c o n t rols in this master, allowing content pages to add con-tent to our content. The design view for BigCorp_Sales.master is shownin Figure 5.8, where you can see that Content1 is the content area definedby BigCorp.master, and Content2 is the region defined for content pagesto use.

Using the nested master page is the same as creating any other contentpage. For example, Listing 5.5 shows a content page using B i g C o r p_Sales.master.

Listing 5.5. A Content Page Using a Nested Master Page

<%@ Page Master="BigCorp_Sales.master" %>

<script runat="server">continues

05ASP.qxd 9/5/03 9:54 AM Page 149

Page 10: Master Pages And Navigation

Sub Page_Load(sender As Object, e As EventArgs)

End Sub

</script>

<asp:Content ContentPlaceHolderId="SalesContentRegion"runat="server">

Welcome to the Big Corp Sales Intranet</asp:Content>

H e re the C o n t e n t P l a c e H o l d e r I d matches the immediate parent, andsince the parent inherits from another page, the ultimate result is a combi-nation of both master pages and the child ASP.NET content page. So, if wehave two child content pages, one for the sales division and one for the re-search division, we’ll end up with a site as shown in Figure 5.9.

M ASTER PA G E S AND NAV I G AT I O N150

Figure 5.9. Using nested master pages

05ASP.qxd 9/5/03 9:54 AM Page 150

Page 11: Master Pages And Navigation

In Figure 5.9 you can see that although both departments have chosena diff e rent style of menu (one vertical and one horizontal), the top of thepage remains constant because it is defined in the top-level master.

Master Page ConfigurationAttaching a master page directly to a page provides great flexibility butdoes have a downside. Not only must developers know the name of themaster but they are also free to not use it, which could result in pages notfitting with the overall site design. To ensure that a master page cannot beomitted, master pages can be attached globally by modifying the Web con-figuration file, as shown in the following fragment:

<configuration><system.web>

<pages master="BigCorp.master" />

</system.web></configuration>

A master page attached locally via the M a s t e r attribute, however, over-rides any global master pages defined in web.config.

Device-Specific Master PagesA S P.NET has a new arc h i t e c t u re for detecting and rendering content tomobile devices, and this control arc h i t e c t u re has also been implemented bythe master page processing, enabling different master pages to be used ford i ff e rent devices. For example, it would be possible to supply diff e re n tmaster pages for Internet Explorer and Mozilla. This is achieved by creat-ing separate master pages and then in the page pre fixing the m a s t e r a t-tribute with the name of the device, as shown below:

<%@ Page master="default.master"Mozilla:master="mozilla.master" %>

When this page is accessed by a Mozilla bro w s e r, m o z i l l a . m a s t e r is used.All other browsers use the default master page. The results can be seen inFigure 5.10, where the content simply differs for each browser. Where thiscomes into its own is in supporting multiple devices, such as small-screendevices, where your master page might need to be very different, perhapsto incorporate a different menu structure.

Mobile device support is covered in more detail in Chapter 10.

M ASTER PA G ES IN DETA I L 151

05ASP.qxd 9/5/03 9:54 AM Page 151

Page 12: Master Pages And Navigation

Event OrderingBecause events can be present in both the master and content pages, theevent order follows that of User Controls. So, for events that are capturedtwice, such as the P a g e _ L o a d event, the content page event is fired first.

Accessing the Master PageContent pages that have a master have a pro p e r t y, M a s t e r, allowing accessto the master page. The Master property returns an instance of Page (fromS y s t e m . W e b . U I), and thus you can access all of the properties and meth-ods in the same way as for other pages. For example, to access a contro lf rom the master page you can do one of two things. The first option is toexpose the control through a public property on the master page (Listing5.6) and access that property from the content page (Listing 5.7).

M ASTER PA G E S AND NAV I G AT I O N152

Figure 5.10. Device-specific master pages

Like the rest of the device-specific features, the list of devices can befound in the C O N F I G d i rectory under the .NET Framework installationd i re c t o r y. These are device capability files, detailing the exact fea-tures of each browser.

05ASP.qxd 9/5/03 9:54 AM Page 152

Page 13: Master Pages And Navigation

Listing 5.6. Exposing Master Page Properties (MySite.master)

<%@ Master %><script runat="server">

Public ReadOnly Property home() As HyperlinkGetReturn home

End GetEnd Property

</script>

<form runat="server">

<asp:Hyperlink id="home"NavigateUrl="default.aspx" />

</form>

Listing 5.7. Accessing Exposed Master Page Properties (MyPage.aspx)

<%@ Page Master="MySite.master" %><script runat="server">

Sub Page_Load(sender As Object, e As EventArgs)

Dim Url As String = Page.Master.Home.NavigateUrl

End Sub

</script>

Listing 5.6 shows a master page with a control exposed as a P u b l i cP r o p e r t y, and Listing 5.7 shows a content page accessing that contro lthrough the exposed property.

The second approach is to access the controls late bound and use theFindControl method to find the controls, as shown in Listing 5.8.

Listing 5.8. Accessing Master Page Contents Late Bound

<%@ Page Master="MySite.master" %><script runat="server">

Sub Page_Load(sender As Object, e As EventArgs)

Dim Url As String = _CType(Master.FindControl("home"), _

Hyperlink).NavigateUrl

M ASTER PA G ES IN DETA I L 153

continues

05ASP.qxd 9/5/03 9:54 AM Page 153

Page 14: Master Pages And Navigation

End Sub

</script>

While the first solution does re q u i re you to expose controls as pro p e r-ties, this is re q u i red only for controls that are needed external to the mas-ter page, and this approach does provide a more efficient solution than thelate-bound approach.

NavigationThe importance of good navigation on a site cannot be underestimated. Itdoesn’t matter how great your site looks or how well it was developed—ifit’s hard to navigate, users won’t like using it. It’s easy to see how seriouslynavigation is taken just by looking at the number of menu controls thathave been written since A S P.NET 1.0 was re l e a s e d — t h e re are now contro l sthat use tree views, vertical expansion, horizontal layouts, flashy graphics,and so on.

P roviding a good menu isn’t the end of site navigation because it’s im-portant to ensure visitors know where they are within the site hierarchy.Too often we see sites with pages three or four levels deep within the menustructure, but when we navigate to those pages there’s no indication ofw h e re we are. We are left wondering how to navigate back up the stru c t u re ;at worst, we have to go back to the home page to navigate down again.

Site MapsThere are plenty of ways to implement navigation on a site, but none thata re an intrinsic part of A S P.NET 1.x. With A S P.NET 2.0, there are contro l sand configuration files for providing a set way to define site structure andtechniques for displaying the navigation information and extracting thecurrent navigation path.

Like the rest of A S P. N E T, the arc h i t e c t u re for navigation has been bro-ken down into logical parts, allowing customization. First, there is a con-figurable provider supplying the site map information, and then a set ofcontrols that can take advantage of the data supplied by the provider. Thep rovider not only exposes the site stru c t u re to other controls but also keepstrack of the current navigation, allowing pages to identify where in the hi-e r a rchy they are. The entire stru c t u re and the current details can be ex-posed to users by binding controls to the pro v i d e r. This pluggablearchitecture means that data defining the structure of a site can come from

M ASTER PA G E S AND NAV I G AT I O N154

05ASP.qxd 9/5/03 9:54 AM Page 154

Page 15: Master Pages And Navigation

any data source—the site map provider is the link between the data andthe navigation within a site.

Site Map ProvidersA site map provider is a data provider that exposes the site stru c t u re byway of a set interface. Site maps are pluggable within the application con-figuration file, within the s y s t e m . w e b section. The syntax for this section isshown in Listing 5.9.

Listing 5.9. Site Map Configuration Syntax

<siteMapdefaultProvider="string"enabled="[true|false]">

<providers><add

name="string"description="string"provider-specific-configuration />

<removename="string" />

<clear></providers>

</siteMap>

The attributes for the siteMap element are shown in Table 5.1.The attributes for the providers element are shown in Table 5.2.

Table 5.1. siteMap Configuration

Attribute Description

defaultProvider The name of the default provider. This should match oneof the names supplied in the providers section.

enabled A Boolean value indicating whether or not site maps areenabled.

Table 5.2. siteMap providers Configuration

Attribute Description

name The name of the site map provider.

description A description of the provider.

type A string containing the full .NET type of the provider.

N AV I G AT I O N 155

05ASP.qxd 9/5/03 9:54 AM Page 155

Page 16: Master Pages And Navigation

Table 5.3. XmlSiteMapProvider-Specific Attribute

Attribute Description

siteMapFile The name of the XML file containing the site structure.The file name is configured as app. SiteMap.

With the Technology Preview of A S P.NET 2.0, the only provider is theXmlSiteMapProvider (in System.Web), allowing site navigation structureto be stored in an XML file. For a full description of the type attribute, seethe m a c h i n e . c o n figfile. The X m l S i t e M a p P r o v i d e r has one pro v i d e r- s p e-cific attribute, as shown in Table 5.3.

The pluggable architecture makes it extremely easy to add support foradditional methods of site map storage. For example, you could write aF rontPage site map provider to read the site stru c t u re from the formatused by Microsoft FrontPage, or perhaps one to build the stru c t u re fro mthe file system, directly reading the names of the files and directories. Towrite your own site map provider you need to implement the I S i t e M a p-P r o v i d e r interface. A discussion of this is outside the scope of the book,but details of the interface can be found in the documentation.

Site Map Configuration FilesThe X m l S i t e M a p P r o v i d e r d e fines a set schema for the a p p . S i t e M a p fil e ,as shown in Listing 5.10.

Listing 5.10. XmlSiteMapProvider Schema

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"elementFormDefault="qualified">

<xs:element name="siteMap"><xs:complexType>

<xs:sequence><xs:element ref="siteMapNode"

maxOccurs="unbounded"/></xs:sequence>

</xs:complexType></xs:element><xs:element name="siteMapNode">

<xs:complexType><xs:sequence><xs:element ref="siteMapNode" minOccurs="0"

MaxOccurs="unbounded"/></xs:sequence><xs:attribute name="url" type="xs:string"/>

M ASTER PA G E S AND NAV I G AT I O N156

05ASP.qxd 9/5/03 9:54 AM Page 156

Page 17: Master Pages And Navigation

<xs:attribute name="title" type="xs:string"/><xs:attribute name="description" type="xs:string"/><xs:attribute name="keywords" type="xs:string"/><xs:attribute name="roles" type="xs:string"/><xs:attribute name="SiteMapFile" type="xs:string"/><xs:attribute name="Provider" type="xs:string"/>

</xs:complexType></xs:element>

</xs:schema>

This defines a structure consisting of a root siteMap element, with thesite stru c t u re being contained by s i t e M a p N o d e elements. There has to beone top-level siteMapNode element, and within that can be any number ofs i t e M a p N o d e elements of any depth. The attributes for the s i t e M a p N o d eelement are shown in Table 5.4.

The use of S i t e M a p F i l e allows the site map information to be splitamong different sources. This is especially useful when different divisionssupply sections of a corporate site—each part of the site map can be au-thored independently and even stored in different providers.

Listing 5.11 shows a sample site map file. To create one within Vi s u a lStudio .NET “Whidbey”, you simply create a new XML file and call itapp.SiteMap—there isn’t a template for this.

Table 5.4. siteMapNode Attributes

Attribute Description

url The URL to be used to navigate to the node. This must beunique within the entire site map file.

title The title of the node.

description A description of the node.

keywords Keywords used to describe the node. Multiple keywordscan be separated by semicolons (;) or commas (,).

roles A list of roles allowed to view the node. Multiple roles canbe separated by semicolons (;) or commas (,).

SiteMapFile An external file containing additional siteMap nodes.

Provider The name of the site map provider that will supply addi-tional nodes specified in SiteMapFile.

N AV I G AT I O N 157

05ASP.qxd 9/5/03 9:54 AM Page 157

Page 18: Master Pages And Navigation

Listing 5.11. Sample app.SiteMap File

<siteMap><siteMapNode title="Home"

description="Home"url="SiteMaps.aspx?id=1">

<siteMapNode title="Sales"description="The Sales Site"url="SiteMaps.aspx?id=2">

<siteMapNode title="Customers"url="SiteMaps.aspx?id=3"/>

<siteMapNode title="Products"url="SiteMaps.aspx?id=4/>

<siteMapNode title="Region"url="SiteMaps.aspx?id=5"/>

<siteMapNode title="Futures"url="SiteMaps.aspx?id=6"/>

</siteMapNode><siteMapNode title="Research"

description="The Research Site"url="SiteMaps.aspx?id=7">

<siteMapNode title="Widgets"url="SiteMaps.aspx?id=8"/>

<siteMapNode title="Doodads"url="SiteMaps.aspx?id=9"/>

<siteMapNode title="Thingies"url="SiteMaps.aspx?id=10" />

</siteMapNode></siteMapNode>

</siteMap>

This provides the following structure for the site:

HomeSales

CustomersProductsRegionFutures

ResearchWidgetsDoodadsThingies

Using a Site Map FileOnce the stru c t u re of your site is defined in the site map file, you then needa way to make use of it. For this you use a S i t e M a p D a t a S o u r c e c o n t ro l ,which provides data access to the site map data, and then a control to dis-play that data. From within Visual Studio .NET “Whidbey”, you can just

M ASTER PA G E S AND NAV I G AT I O N158

05ASP.qxd 9/5/03 9:54 AM Page 158

Page 19: Master Pages And Navigation

drag a S i t e M a p D a t a S o u r c e c o n t rol onto the design surface—there’s noneed to set any properties because it defaults to using a p p . S i t e M a p as itsdata source. You can then drag a T r e e V i e w c o n t rol onto the page and set itsDataSourceId property to the id of the SiteMapDataSource control. Fig-u re 5.11, for example, shows how our Big Corp site could be constru c t e dusing a single menu.

Other controls can be bound to site map data, but in the Te c h n o l o g yPreview release, the TreeView provides the best option because of its hier-archical display. It’s likely that a dedicated menu control will appear in fu-ture versions.

Site Maps in DepthAt its simplest, the use of site maps needs nothing more than has been dis-cussed above, but there’s actually more to them. Adding a S i t e M a p D a t aSource control to a page provides all that’s needed for site map handling,but there are properties that allow for more control over how the data issupplied from the S i t e M a p D a t a S o u r c e to controls. For example, the syn-tax of the SiteMapDataSource control is shown in Listing 5.12.

N AV I G AT I O N 159

Figure5.11. A TreeView bound to a SiteMapDataSource

05ASP.qxd 9/5/03 9:54 AM Page 159

Page 20: Master Pages And Navigation

Listing 5.12. SiteMapDataSource Syntax

<asp:SiteMapDataSource id="String" runat="server"FlatDepth="Integer"SiteMapProvider="String"SiteMapViewType="[Flat|Path|Tree]"StartingDepth="Integer"StartingNodeType="[Current|Parent|Root]"StartingNodeUrl="String"

/>

The attributes are shown in Table 5.5.

Table 5.5. SiteMapDataSource Attributes

Attribute Description

FlatDepth A number that defines how many nodes deep in thehierarchical structure are flattened. The default is -1,which indicates all nodes.

SiteMapProvider The name of the provider supplying the site map data.

SiteMapViewType One of the SiteMapViewType enumerations, whosevalues are:

• Flat: Indicates that the data is presented withoutany structure.

• Path: Indicates the data presented is a list of nodesbetween the root node and the current node.

• Tree: Indicates the data is presented in the samehierarchical structure as the original data source.Binding nonhierarchical controls when using this modeshows only the top level of the hierarchy. This is thedefault value.

StartingDepth Specifies the node depth at which to start representingdata. The default is 0, which is the first node.

StartingNodeType One of the SiteMapNodeType enumerations, whosevalues are:

• Current: Indicates the node that represents thecurrently displayed page.

• Parent: Indicates the parent node of the currentlydisplayed page.

• Root: Indicates the root node. This is the defaultvalue.

StartingNodeUrl The URL of the node at which to start representing data.

M ASTER PA G E S AND NAV I G AT I O N160

05ASP.qxd 9/5/03 9:54 AM Page 160

Page 21: Master Pages And Navigation

The effects of some of these properties are not immediately appare n tand depend on which control you bind to the data source and where youa re in the navigation hierarc h y. Probably the most useful control is theT r e e V i e w, which naturally displays hierarchical data, but the L i s t B o x i salso good for displaying site map data in a flat view. A good way to see thee ffects of these properties is to build a grid with three S i t e M a p D a t a S o u r c ec o n t rols, each set to a diff e rent S i t e M a p V i e w T y p e. Then you can bind aT r e e V i e w and a L i s t B o x to each type view of the site map, as shown inListing 5.13.

Listing 5.13. Sample Site Map Displays

<asp:SiteMapDataSource id="SiteDataFlat" runat="server"SiteMapViewType="Flat" />

<asp:SiteMapDataSource id="SiteDataPath" runat="server"SiteMapViewType="Path" />

<asp:SiteMapDataSource id="SiteDataTree" runat="server"SiteMapViewType="Tree" />

<table border="1" width="50%"><tr><td>Flat</td><td>Path</td><td>Tree</td>

</tr> <tr><td>

<asp:TreeView runat="server"DataSourceId="SiteDataFlat" />

</td><td>

<asp:TreeView runat="server"DataSourceId="SiteDataPath" />

</td><td>

<asp:TreeView runat="server"DataSourceId="SiteDataTree" />

</td></tr> <tr><td>

<asp:ListBox runat="server"DataSourceId="SiteDataFlat" />

</td><td>

<asp:ListBox runat="server"DataSourceId="SiteDataPath" />

</td><td>

N AV I G AT I O N 161

continues

05ASP.qxd 9/5/03 9:54 AM Page 161

Page 22: Master Pages And Navigation

<asp:ListBox runat="server"DataSourceId="SiteDataTree" />

</td></tr>

</table>

The initial display is shown in Figure 5.12. By default the T r e e V i e wbinds the title attribute of the site map to the Text property and the urlattribute to the N a v i g a t e U r l p ro p e r t y, giving you an instant menu contro l .For the L i s t B o x the t i t l e attribute is bound to both the D a t a T e x t F i e l dand DataValueField properties.

You can see from this that when in Tree mode, the TreeView displaysas you expect it to. However, the F l a t view shows how all nodes (at what-ever level) are shown. Nodes with children are expandable in the normalTreeView style. For the Path mode, nothing is shown because we haven’tyet performed any navigation.

For the L i s t B o x c o n t rol, the T r e e mode shows only the first node be-cause it is a naturally flat control and can deal only with a single level ofthe hierarc h y. However, in F l a t mode you see all nodes because they havebeen flattened and therefore appear at the top level.

The results of navigating to the Sales Re g i o n page are shown in Figure 5.13.H e re you can see that the T r e e and F l a t views are essentially the same,

and the Path view has now been filled. In the Path view column, note thatthe T r e e V i e w contains the same data as the T r e e mode, but the L i s t B o xshows only those nodes in the path between the root node and the selectednode.

M ASTER PA G E S AND NAV I G AT I O N162

Figure 5.12. Initial site map display

05ASP.qxd 9/5/03 9:54 AM Page 162

Page 23: Master Pages And Navigation

Flattening NodesSetting the FlatDepth property limits the depth of the nodes that are flat-tened. For example, on the left in Figure 5.14 you see a FlatDepth of 1, soonly one node is flattened. On the right a F l a t D e p t h of 2 causes thre enodes to be flattened—the top node, plus its two child nodes.

Setting the Starting DepthThe StartingDepth property indicates at which node level the data is dis-played from, and it affects all three modes (Flat, Path, and Tree). For ex-ample, setting the S t a r t i n g D e p t h to 1 ( w h e re no F l a t D e p t h is set) isshown in Figure 5.15.

H e re you can see that only nodes from level 1 down are shown andonly those from our navigation point—re m e m b e r, the S i t e M a p D a t aSource keeps track of where we are in the navigational structure.

N AV I G AT I O N 163

Figure 5.14. Results of setting different FlatDepth properties

Figure 5.13. Navigating to a page

05ASP.qxd 9/5/03 9:54 AM Page 163

Page 24: Master Pages And Navigation

Setting the Starting Node TypeThe StartingNodeType property identifies what type of node to start dis-playing data from. For example, setting this property to Parent w o u l dgive the results in Figure 5.16. We’ve navigated to the R e g i o n node, a nodethat is underneath S a l e s. In the L i s t B o x, for the F l a t view we see onlythe Parent of the current node, plus its children; for the Path view, we seeonly the current node and its parent; and for the T r e e v i e w, we see onlythe parent.

Setting the StartingNodeType to Current means that only the currentnode is displayed, as shown in Figure 5.17. Setting the C u r r e n t N o d e T y p eto R o o t means that the current node becomes the root node as far as dis-playing the node hierarchy is concerned.

M ASTER PA G E S AND NAV I G AT I O N164

Figure 5.15. Results of setting the StartingDepth property to 1

Figure 5.16. Results of setting the StartingNodeType property to Parent

Figure 5.16. Results of setting the StartingNodeType property to Parent

05ASP.qxd 9/5/03 9:54 AM Page 164

Page 25: Master Pages And Navigation

Setting the Start Node URLThe S t a r t i n g N o d e U r l p roperty allows us to set the starting point, giventhe URL of a page. Since URLs in the site map file must be unique, this al-lows us to navigate to a given node knowing only the URL, rather than itslocation in the hierarchy.

Showing a Navigation PathWhen a site map provides the navigational architecture for a site, it’s easyto add features that take advantage of this. With a hierarchy three deep orm o re, it has always been hard for users to remember where they are withinthat structure, so the idea of breadcrumbs came about, laying a trail of thepath back to the root of the site.

With A S P.NET 2.0 this is simple: We have the S i t e M a p P a t h c o n t ro l ,which automatically hooks into the site map arc h i t e c t u re, so all you haveto do is drop it on a page, as shown in Figure 5.18.

This fig u re shows the default implementation, just from adding the fol-lowing line of code to our page:

<asp:SiteMapPath runat="server" />

To use the SiteMapPath control you don’t need a SiteMapDataSourcecontrol because it works directly with the site map provider.

The current node is shown as simple text, and parent nodes are shownas hyperlinks, allowing quick navigation up the tree. The text for thetooltip is set to the description attribute from the site map file.

T h e re are plenty of ways to customize this control to fit it to your site.The syntax is shown in Listing 5.14.

N AV I G AT I O N 165

Figure 5.18. The SiteMapPath control

Figure 5.17. Results of setting the StartingNodeType property to Current

05ASP.qxd 9/5/03 9:54 AM Page 165

Page 26: Master Pages And Navigation

Listing 5.14. SiteMapPath Syntax

<SiteMapPath id="String" runat="server"CurrentNodeStyle="Style"CurrentNodeTemplate="Template"HoverNodeStyle="Style"NodeStyle="Style"NodeTemplate="Template"ParentLevelsDisplayed="Integer"PathDirection="[CurrentToRoot|RootToCurrent]"PathSeparator="String"PathSeparatorStyle="Style"PathSeparatorTemplate="Template"RenderCurrentNodeAsLink="Boolean"RootNodeStyle="Style"RootNodeTemplate="Template"ShowToolTips="Boolean"SiteMapProvider="String"/>

These are just the unique properties for this control, described in Table 5.6.All other properties are inherited and are described in the documentation.

Table 5.6. SiteMapPath Properties

Property Description

CurrentNodeStyle Sets or returns the Style object that defines howthe current node is displayed.

CurrentNodeTemplate Sets a Template, allowing customization of howthe current node is displayed.

NodeStyle Sets or returns the Style to be used for nodes.

NodeTemplate Sets a Template, allowing customization of howa node is displayed.

ParentLevelsDisplayed Sets or returns the number of parent levels dis-played. By default all parent levels are displayed.

M ASTER PA G E S AND NAV I G AT I O N166

05ASP.qxd 9/5/03 9:54 AM Page 166

Page 27: Master Pages And Navigation

Table 5.6. SiteMapPath Properties (continued)

Property Description

PathDirection Gets or sets the direction in which the nodes aredisplayed. This can be one of the PathDirec-tion enumerations, whose values are:

• CurrentToRoot: The current node is shownon the left, and child nodes are shown to theright.

• RootToCurrent: The current node is shownon the left, and parent nodes are shown on theright. This is the default value.

Setting the direction has no effect on the separa-tor between nodes.

PathSeparator Sets or returns a string to be used as a separatorbetween nodes. This is replaced by the contents ofthe PathSeparatorTemplate if present. Thedefault is >.

PathSeparatorStyle Sets or returns the Style to be used for thePathSeparator string.

PathSeparatorTemplate Sets a Template, allowing customization of thenode separator.

RenderCurrentNodeAsLink Sets or returns a Boolean that indicates whetheror not the current node is rendered as a hyperlink.The default value is False.

RootNodeStyle Sets or returns the Style to be used for the rootnode. Any Style values set here override thoseset in the NodeStyle property.

RootNodeTemplate Sets a Template, allowing customization of theroot node.

ShowToolTips Sets or returns a Boolean indicating whether ornot tooltips are shown on hyperlinks.

SiteMapProvider Sets or returns a string indicating the site name ofthe provider supplying the site map data.

M ASTER PA G ES IN DETA I L 167

05ASP.qxd 9/5/03 9:54 AM Page 167

Page 28: Master Pages And Navigation

These properties give a great deal of flexibility in how the navigationpath is shown. For example, consider the code shown in Listing 5.15.

Listing 5.15. Setting the SiteMapPath Properties

<asp:SiteMapPath ID="SiteMapPath1" runat="server"NodeStyle-Font-Name="Franklin Gothic Medium"NodeStyle-Font-Underline="true"NodeStyle-Font-Bold="true"RootNodeStyle-Font-Name="Symbol"RootNodeStyle-Font-Bold="false"CurrentNodeStyle-Font-Name="Verdana"CurrentNodeStyle-Font-Size="10pt"CurrentNodeStyle-Font-Bold="true"CurrentNodeStyle-ForeColor="red"CurrentNodeStyle-Font-Underline="false">

<PathSeparatorTemplate><asp:Image runat="server" ImageUrl="arrow.gif"/>

</PathSeparatorTemplate></asp:SiteMapPath>

This defines styles for the nodes and a separator that uses a custom im-age. The results are shown in Figure 5.19.

Notice that the root node is underlined even though it wasn’t specifiedas part of the R o o t N o d e S t y l e—the underlining was inherited from theNodeStyle.

SiteMapPath EventsThe SiteMapPath is built dynamically from the data held by the underly-ing site map pro v i d e r. As the tree of nodes is traversed, each item in thepath, from the root node to the current node, is added to the Controls col-lection of the SiteMapPath control. Like other collection controls (such asthe D a t a L i s t or D a t a G r i d), two events are fired when items are either cre-ated (I t e m C r e a t e d) or bound (I t e m D a t a B o u n d) to the S i t e M a p P a t h. Thesignature for these events is the same:

Sub eventName(Sender As Object,E As SiteMapNodeItemEventArgs)

SiteMapNodeItemEventArgs has one property, Item, which returns anobject of type S i t e M a p N o d e I t e m, which in turn has three properties, as de-scribed in Table 5.7.

M ASTER PA G E S AND NAV I G AT I O N168

Figure 5.19. A customized SiteMapPath control

05ASP.qxd 9/5/03 9:54 AM Page 168

Page 29: Master Pages And Navigation

Table 5.7. SiteMapNodeItem Properties

Property Description

ItemIndex The zero-based index number of the item beingadded.

ItemType The type of node being added, which can be oneof the SiteMapNodeItemType enumerations:

• Current: Indicates the current node (page)within the navigation path.

• Parent: Indicates a parent of the currentnode. All nodes between the current node andthe root node are parent nodes.

• PathSeparator: Indicates a separatorbetween nodes.

• Root: Indicates the root node of thenavigation path.

SiteMapNode The SiteMapNode that represents the nodebeing added to the SiteMapPath.

I n t e rcepting the I t e m C r e a t e d and I t e m D a t a B o u n d events gives you achance to change the default behavior as the items are created. For exam-ple, Listing 5.16 shows how you could build up an HTML m e t a tag con-sisting of the K e y w o r d s f rom the site map details. If the S i t e M a p P a t hcontrol were embedded into the master page, this meta tag would be auto-matically constructed for each page.

Listing 5.16. SiteMapPath ItemCreated Event

<%@ Page %>

<head runat="server" id="PageHead" />

<script runat="server">

Sub ItemCreated(Sender As Object,E As SiteMapNodeItemEventArgs)

If E.Item.ItemType = _SiteMapNodeItemType.Current Then

Dim sb As New StringBuilder()Dim s As String

For Each s In E.Item.SiteMapNode.Keywords

M ASTER PA G ES IN DETA I L 169

continues

05ASP.qxd 9/5/03 9:54 AM Page 169

Page 30: Master Pages And Navigation

sb.Append(s)sb.Append(" ")Next

Dim ctl As New HtmlGenericControl("meta")ctl.Attributes.Add("name", "keywords")ctl.Attributes.Add("content", sb.ToString())PageHead.Controls.Add(ctl)

End IfEnd Sub

</script>

<form runat="server"><asp:SiteMapPath runat="server"

onItemCreated="ItemCreated"/></form>

The SiteMapNode ObjectWhen the site map is constructed from the data provider, each of the itemsis built into a SiteMapNode object. These in turn are added to a SiteMapN-o d e C o l l e c t i o n, which there f o re re p resents all pages within a Web site.The S i t e M a p N o d e object provides links to nodes up, down, and next to itin the hierarchy and thus can be used to build a treelike stru c t u re. A sshown in Listing 5.16, the I t e m C r e a t e d event of the S i t e M a p P a t h o b j e c tallows access to the S i t e M a p N o d e, which has the properties detailed inTable 5.8.

Table 5.8. SiteMapNode Properties

Property Description

Attributes Returns a collection of additional attributes applicableto the node. For the XmlSiteMapProvider, the listof attributes maps to existing properties, namelyTitle, Description, Url, Attributes, Roles,and Keywords.

ChildNodes If applicable, returns a SiteMapNodeCollectioncontaining child nodes of the current node.

Description Returns the description of the current node.

HasChildNodes Indicates whether or not the current node has any childnodes.

M ASTER PA G E S AND NAV I G AT I O N170

05ASP.qxd 9/5/03 9:54 AM Page 170

Page 31: Master Pages And Navigation

Table 5.8. SiteMapNode Properties (continued)

Property Description

Keywords Returns an IList containing keywords for the currentnode.

NextSibling Returns the next node on the same level as the currentnode, or returns null (Nothing in Visual Basic) ifthere is no next node.

ParentNode Returns the parent node of the current node, or returnsnull (Nothing in Visual Basic) if there is no parentnode (i.e., the current node is the root node).

PreviousSibling Returns the previous node on the same level as thecurrent node, or returns null (Nothing in VisualBasic) if there is no previous node.

Roles Returns an IList containing the roles applicable to thecurrent node.

RootNode Returns the root node.

Title Returns the title of the current node.

Url Returns the URL of the current node.

T h e re are three methods for the S i t e M a p N o d e object, as described inTable 5.9.

Table 5.9. SiteMapNode Methods

Method Description

GetAllNodes Returns a SiteMapNodeCollection containing allchild nodes of the current node.

GetDataSourceView Returns a SiteMapDataSourceView, which is aview of the underlying site map data. This is useful forcontrol developers who wish to interface to the site maparchitecture.

IsDescendantOf Indicates whether or not the current node is a descen-dent of a supplied node.

M ASTER PA G ES IN DETA I L 171

05ASP.qxd 9/5/03 9:54 AM Page 171

Page 32: Master Pages And Navigation

Accessing the Site Map at RuntimeSo far we’ve seen the site map be used by controls, but it can also be ac-cessed directly because it is exposed through a static page property calledSiteMap. For example, to access the current node within the site map, youcan use the following code:

Dim currNode As SiteMapNode

currNode = SiteMap.CurrentNode

This means that even if you aren’t using a S i t e M a p P a t h c o n t rol, you caneasily build links pointing back to the hierarchy, as shown in Listing 5.17.

Listing 5.17. Using the SiteMap Property of the Page

<script runat="server">

Sub Page_Load(Sender As Object, E As EventArgs)

ParentLink.NavigateUrl = SiteMap.CurrentNode.ParentNode.Url

End Sub

</script>

<form runat="server">

<asp:HyperLink id="ParentLink" Text="Go Back" />

</form>

Table 5.10 details the properties of the SiteMap class.

Table 5.10. SiteMap Class Properties

Property Description

CurrentNode Returns a SiteMapNode object representing the currentpage.

Provider Returns the site map provider.

Providers Returns a collection (SiteMapProviderCollection)of all site map providers.

RootNode Returns a SiteMapNode object representing the rootnode.

M ASTER PA G E S AND NAV I G AT I O N172

05ASP.qxd 9/5/03 9:54 AM Page 172

Page 33: Master Pages And Navigation

These properties give you access to the site map details and allow youto interface into it at the programmatic level, in case more flexibility is re-quired than the standard server controls provide.

SUMMARY

In this chapter we’ve looked at two very important topics: how the lookand feel of sites can be implemented in A S P.NET 2.0 and how navigationaround those sites can be implemented.

We’ve seen how a great deal of time-consuming work has been re-moved by the introduction of master pages, allowing the site layout anddefault implementation to be easily centralized. Not only does this make iteasier to develop individual pages, but since layout and code can be cen-trally contained, it also eases maintenance and reduces potential erro r s .

We’ve also seen how A S P.NET 2.0 supplies a comprehensive arc h i t e c-t u re for site navigation. The introduction of the S i t e M a p D a t a S o u r c e a n dthe underlying flexibility of providers allow site stru c t u re to be easily de-fined and used within Web pages. By placing this navigation within a mas-ter page you also have the simplicity of having to define the navigation inonly a single place.

Now it’s time to move on to another important topic—security, and howto identify users and control what they can do once they reach your site.

S U M M A RY 173

05ASP.qxd 9/5/03 9:54 AM Page 173