M. J. Kahn Software Development and Management Consultant
Skip Navigation Links.

Adding Targets to ASP.NET SiteMaps

ASP.NET allows you to define a SiteMap that reflects the hierarchy of pages on your web site. You define a SiteMap by creating a web.sitemap file and then defining a SiteMapDataSource that refers to the web.sitemap file. You then make the SiteMap visible to users by adding a UI control (like a TreeView) to a page in your site, and binding the UI control to the SiteMapDataSource.

When you define an element in your SiteMap, you can specify the element's URL, title, and description. For example:

   <siteMapNode url="~/About.aspx" title="Home" description="About MJ" />

However, you can't specify a target attribute in a siteMapNode element. If you want a page defined in your SiteMap to appear in a different window, you can't say so in the web.sitemap file. So how can you add a target designation to a siteMapNode entry?

The answer is to add the target programmatically, just after the UI control is bound to the SiteMapDataSource. In the UI control's DataBound event, iterate over the SiteMapNode items to find the ones you want to open in a new window, and set their Target attribute to the name of the new window.

For example, the code below finds all SiteMapNode items whose URL starts with "http" and sets their target to "newwin." With this code in place, all URLs that refer to external web sites will open in a separate window.

' Handle the DataBound event for the page's TreeView UI control
Protected Sub TreeView1_DataBound(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles TreeView1.DataBound
  ' We want all external URLs to open in a new window, so run through the sitemap
  ' after it's bound, find all the URLs that start with "http" (includes "https"),
  ' and set their target programmatically to open in a new window.
  For i As Integer = 0 To Me.TreeView1.Items.Count - 1
    For j As Integer = 0 To Me.TreeView1.Items(i).ChildItems.Count - 1
      If Me.TreeView1.Items(i).ChildItems(j).NavigateUrl.StartsWith("http") Then
        Me.TreeView1.Items(i).ChildItems(j).Target = "newwin"
      End If
    Next
  Next
End Sub

Was this tip helpful? If so, please drop MJ a note to say so.