Skip navigation

Automate Navigation Chores

Streamline Web Site Maintenance with Site Maps and the New Navigation Controls of ASP.NET 2.0

ControlFreak

LANGUAGES: VB.NET

ASP.NET VERSIONS: 2.0

 

Automate Navigation Chores

Streamline Web Site Maintenance with Site Maps and the New Navigation Controls of ASP.NET 2.0

 

By Steve C. Orr

 

In this article you ll learn how to use Site Maps to provide a consistent and easy mechanism for updating a Web site s perceived structure. You ll learn how to bind a basic Site Map file to the new Menu, TreeView, and SiteMapPath controls. You ll also learn how to extend Site Maps with additional metadata, and how to consume that information in useful ways. To top it all off, you ll learn how to use the default SiteMapPath provider to create your own custom navigational structure that will perform auto update functions.

 

New ASP.NET 2.0 Navigation Controls

The new Menu, TreeView, and SiteMapPath controls provided with ASP.NET 2.0 are nice additions to virtually any Web site. When combined with a SiteMap provider, the productivity gains become nearly explosive. These controls can be found on the Navigation tab of the Visual Studio 2005 toolbox, as shown in Figure 1; Figure 2 shows these controls in action at run time.

 


Figure 1: The new Navigation controls included in Visual Studio 2005 are powerful new tools that all Web developers should get to know.

 


Figure 2: The new Menu, TreeView, and SiteMapPath navigation controls (pictured here in blue) can be bound to a common SiteMapDataSource so they stay in sync even when the structure of your site changes.

 

Before ASP.NET 2.0, if you wanted a dropdown menu control you d either have to buy a third-party control or create one yourself (involving plenty of JavaScript, this is not a simple task). The new ASP.NET 2.0 Menu control saves us from such headaches. After dropping one onto a Web form, you can add or remove menu items through its Items collection in the properties window. A nice user interface (shown in Figure 3) is provided to make the work relatively intuitive.

 


Figure 3: The new Menu control in ASP.NET 2.0 provides an intuitive Menu Item Editor dialog box through which you can configure the menu items that will be displayed and nest them as deeply as necessary. A similar dialog box is available for the new TreeView control.

 

The Menu control has rich functionality, including dozens of properties to customize the look and behavior of the menu. For example, the Orientation property lets you specify whether the menu should have a vertical or horizontal layout. Menus can be nested as deeply as needed, and each level can have its own formatting, if desired. Sub items can even be set to scroll if the list becomes too large.

 

The new SiteMapPath control acts a lot like a trail of bread crumbs that shows the user where they currently are in the Web site and gives them a simple path back to the upper levels. The familiar interface looks a lot like this (by default):

 

Home > Software > Utilities

 

Of course, there are a couple dozen properties available that allow you to adjust the appearance in nearly any way imaginable. For example, the boolean RenderCurrentNodeAsLink property allows you to specify whether the current page s node appears as a hyperlink or simple text. With the ParentLevelsDisplayed property you can control the number of levels that are displayed in cases where the Web site hierarchy is so deep that you don t want to confuse the user with too many options. The default (-1) imposes no limits.

 

The new TreeView control is quite versatile. It can be used for navigational purposes, as well as other data-related purposes. To edit the node hierarchy that will be displayed by the TreeView control, you can click its Nodes ellipses button in the Properties window to display an intuitive dialog box nearly identical to the one shown in Figure 3. The TreeView control is one of the most functionally rich controls in ASP.NET 2.0, and deserves an article of its own.

 

Although the controls cited to this point can all have their hierarchical elements configured independently, this can prove to be a maintenance nightmare for a large site that adds and modifies content on a regular basis. Luckily, there are some good solutions. One way to simplify things is to put common navigation components into a Master Page that all (or most) of the pages use. However, if you have multiple Master Pages, or use multiple navigation controls, this still leaves maintenance chores that can be eased even further.

 

On the Data tab of the Visual Studio 2005 toolbox you ll find the new SiteMapDataSource component. By dragging it onto a Web form, your navigation controls can have automatic access to a common SiteMap by setting their DataSourceID properties to the ID of the SiteMapDataSource component. Using this technique, all navigational controls can automatically stay in sync with each other. So what exactly is a SiteMap?

 

The web.sitemap File

A SiteMap file is an XML file that describes the logical structure of a Web site. To add a SiteMap file to a Web application in Visual Studio 2005, right-click on the project in solution explorer and choose Add Item. From the resulting dialog box, select Site Map (as shown in Figure 4). Figure 5 shows an example of a fairly typical web.sitemap file.

 


Figure 4: Visual Studio 2005 supports SiteMap files so navigation controls can be configured to use a common data source.

 

 

 

               title="Software"

                description="Software">

   

                   title="Financial"

                   description="Financial" />

  

                 title="Office Suites"

                  description="Office Suites" />

  

                 title="Operating Systems"

                  description="Operating Systems" />

  

                  title="Utilities"

                 description="Utilities" />

 

 

                title="Hardware"

               description="Hardware">

   

                  title="Computers"

                  description="Computers" />

   

                  title="Keyboards"

                  description="Keyboards" />

  

                   title="Mice"

                description="Mice" />

   

                  title="Monitors"

                 description="Monitors" />

 

 

               title="Books"

              description="Books">

  

                  title="Fiction"

                description="Fiction" />

  

               title="Finances"

                  description="Finances" />

  

                title="Religion"

                description="Religion" />

  

                  title="Music"

                description="Music"

                  customicon="175" />

  

                 title="Science"

                description="Science"

                  customicon="126"

                  customiconcolor="gold"/>

 

 

Figure 5: SiteMap files can store the logical structure of a Web site, which may or may not match the physical structure of the site. A SiteMapProvider can read this file to reflect changes instantly on every page throughout an entire Web site.

 

A SiteMap file contains many nested SiteMapNodes. Each SiteMapNode is intended to represent a page and/or a category of pages. You can see in the example illustrated in Figure 5 that I ve added three primary categories (Software, Hardware, and Books) that contain several pages each. SiteMapNode elements typically contain three attributes (remember that XML is case sensitive):

  • url. Lists the page to which the user will be sent when they click on a link that represents this SiteMapNode.
  • title. Contains the text that will be displayed to represent the page.
  • description. Represents the tooltip that will be displayed when the user hovers their mouse over the link.

The final two nodes in Figure 5 demonstrate that custom attributes can optionally be added to SiteMapNodes to contain any extra custom data you d like to be associated with pages. For these extra attributes to be useful, though, you ll need to write code that does something useful with them (as demonstrated later in this article).

 

Although custom attributes can be added to a SiteMap file, custom elements unfortunately cannot; all elements must be SiteMapNodes. The only exception would be if you create a customized SiteMapProvider that can accept custom elements. To learn more about creating custom SiteMapProviders, start by reading Custom Site Map Providers in ASP.NET 2.0 located at http://msdn.microsoft.com/library/en-us/dnaspp/html/custsitemap.asp.

 

Using the SiteMap Object

Although it s nice that the new navigation controls in ASP.NET 2.0 provide automatic use of the SiteMap, what do you do if you d like to use a different control? For example, the VisiPanel control could make a nice navigational control. The code in Figure 6 works with the built-in SiteMap object to fill VisiPanel controls with hyperlinks represented in the web.sitemap file.

 

Protected Sub Page_Load(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles Me.Load

 For Each SMN As SiteMapNode In SiteMap.RootNode.ChildNodes

   MakePanel(SMN)

 Next

End Sub

Private Sub MakePanel(ByVal SMN As SiteMapNode)

 Dim pnl As VisiPanel.VisiPanel = New VisiPanel.VisiPanel()

 pnl.BorderWidth = 1

 pnl.BorderStyle = BorderStyle.Solid

 pnl.HeaderText = SMN.Title

 'loop through each child node

 'and create a hyerlink to the page.

 For Each Child As SiteMapNode In SMN.ChildNodes

   pnl.Controls.Add(New LiteralControl(" "))

   If Child.Url.Length > 0 AndAlso _

     SiteMap.CurrentNode.Url = Child.Url Then

     'if the link is to the current page

     'then don't display a hyperlink

     pnl.Controls.Add(New LiteralControl("" & _

        Child.Title & ""))

   Else

     'display a hyperlink to the page

     Dim h As WebControls.HyperLink = _

       New WebControls.HyperLink()

     h.NavigateUrl = Child.Url

      h.Text = Child.Title

     h.ToolTip = Child.Description

     pnl.Controls.Add(h)

   End If

   CreateIcon(Child, pnl)

   pnl.Controls.Add(New LiteralControl("
"))

 Next

 ChoosePanelColors(pnl)

 pnlMain.Controls.Add(pnl)

 pnlMain.Controls.Add(New LiteralControl("
"))

End Sub

Figure 6: The SiteMap object is used in this example to iterate through the web.sitemap nodes and fill VisiPanel controls dynamically with the appropriate hyperlinks.

 

The Page_Load event loops through the top level nodes in the SiteMap and calls the custom MakePanel subroutine once for each node. The MakePanel function starts by instantiating a VisiPanel control and configuring a few basic properties. It then loops through the child nodes of the SiteMapNode parameter. If the node represents the current page, the Title of the node is then displayed as simple text via the LiteralControl class. Otherwise, a hyperlink is instantiated to create a link to the page. The Url, Title, and Description properties of the SiteMapNode object are used to retrieve the url, title, and description values from the SiteMapNode of the web.sitemap file, respectively. The hyperlink is then added to the VisiPanel s Controls collection. A couple other custom functions (shown in Figure 7) are called to deal with customizations before the final couple lines add the completed VisiPanel to the page s main panel.

 

Private Sub CreateIcon(ByVal Node As SiteMapNode, _

                      ByVal pnl As Panel)

 If Node("customicon") IsNot Nothing Then

    Dim lblIcon As New Label()

   lblIcon.Font.Name = "webdings"

   lblIcon.Text = Chr(CInt(Node("customicon")))

   If Node("customiconcolor") IsNot Nothing Then

     lblIcon.ForeColor = _

       Drawing.Color.FromName(Node("customiconcolor"))

   End If

     pnl.Controls.Add(lblIcon)

 End If

End Sub

Private mPanelsCount As Integer = 0

Private Sub ChoosePanelColors(ByVal pnl As VisiPanel)

 Select Case mPanelsCount

   Case 0

     pnl.BackColor = Drawing.Color.Pink

     pnl.GradientEndColor = Drawing.Color.Red

   Case 1

     pnl.BackColor = Drawing.Color.LightGreen

     pnl.GradientEndColor = Drawing.Color.GreenYellow

   Case 2

     pnl.BackColor = Drawing.Color.LightCyan

     pnl.GradientEndColor = Drawing.Color.Cyan

 End Select

 mPanelsCount += 1

End Sub

Figure 7: These two helper functions create custom icons for each appropriately configured SiteMapNode and set the background colors for each VisiPanel control.

 

The CreateIcon function shown in Figure 7 uses the customicon and customiconcolor attributes that were added to the web.sitemap file. When these optional attributes are found in a node, the specified character is displayed in the Webdings font and with the specified color. The ChoosePanelColors function decides which background color gradients should be used for the VisiPanel. This example allows up to three VisiPanels to be present with attractively configured colors, although more can easily be added. Figure 8 shows all of this code in action. Notice the custom icons for the music and science links in the bottom VisiPanel.

 


Figure 8: Last month s VisiPanel control is used in conjunction with the ASP.NET 2.0 SiteMap object to dynamically output the logical structure of the Web site in an attractive and easily navigable way.

 

Conclusion

The navigation controls of ASP.NET 2.0 are a powerful new asset. Although the navigational hierarchies they expose can be configured independently, most large sites will benefit from using a SiteMap to tie them all to a common data source. In the rare case that these new controls don t meet your requirements, you can write a little code that uses the SiteMap object to create your own user interface that takes advantage of the web.sitemap file. You can extend the SiteMapNodes in the web.config file with custom attributes that allow you to mark pages with special flags you can use in your code.

 

By centralizing the structure of a Web site into a single file, the entire Web site s perceived structure can be changed instantaneously without needing to recompile or restart the application. The only question that remains is what you ll do with all the spare time you have now that Web site navigational chores have been reduced to nearly nothing.

 

The code in this article was developed with Visual Studio 2005 release candidate 1. It s possible (although unlikely) that breaking syntax changes could happen before the final release.

 

Steve C. Orr is an MCSD and a Microsoft MVP in ASP.NET. He s an independent consultant that develops software solutions for many leading companies in the Seattle area, such as Microsoft, Lumedx, and The Cadmus Group. When he s not busy designing software systems or writing about it, he can often be found loitering at local user groups and habitually lurking in the ASP.NET newsgroup. Find out more about him at http://Steve.Orr.net or e-mail him 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