Using the SiteMapDataSource to display lists of links

Danny Chen just blogged about the SiteMap and showed some interesting ways to make use of custom attributes:

   http://weblogs.asp.net/dannychen/archive/2005/03/28/396099.aspx

There's another one that I'd like to add to this list.  Commonly people are using UL elements to create navigational links because they require less Html to be emitted in the page and are easily styled into nice looking links.  This is the approach that modern applications such as CommunityServer and ProjectDistributor use for their lists of links.  So how would you do that with a SiteMap?  The answer is actually pretty simple because you can bind a SiteMapDataSource directly to a Repeater.

  <ul>
    <asp:Repeater DataSourceId="myDataSource" ...>
      <ItemTemplate>
        <li>
          <a href='<%# Eval("Url") %>'><%# Eval("Title") %></a>
        </li>
      </ItemTemplate>
    </asp:Repeater>
  </ul>

<asp:SiteMapDataSource id="myDataSource" runat="server" ShowStartingNode="false" />

That will give you a nice list of clickable links.

On my site I actually only required a subset of the items in the SiteMap to be rendered on a specific menu.  For example, I had a left navigation menu which only displays a subset of the total items.  In this case I can use the technique that Danny showed off by adding a custom attribute to my SiteMapNode's like so:

  <?xml version="1.0" encoding="utf-8" ?>
  <siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
    <siteMapNode url="Home.aspx" title="Home"  DisplayOnLeft="true">
      <siteMapNode url="Work.aspx" title="Work" />
      <siteMapNode url="School.aspx" title="School" DisplayOnLeft="true" />
    </siteMapNode>
  </siteMap>

So, you can see that 2 of the nodes contain a DisplayOnLeft attribute which is set to true.  Now, to conditionally display those items in my sidebar navigation list I can hook the Repeater's ItemDataBound event and write logic like so...

  SiteMapNode node = e.Item.DataItem as SiteMapNode ;
  string display = node["DisplayOnLeft"];
  if( string.IsEmptyOrNull( display ) || display != "true" ) {
     e.Item.Visible = false ;
  }

11 Comments

Comments have been disabled for this content.