Friday, February 29, 2008

Tweaking the SiteMap Navigation Menu

I have a site that uses a SiteMap provider and a Menu control for the site's navigation controls. Using the SiteMap provider is a simple and quick way to get dynamic menu for your site. Everything was going along smoothly until I was asked to have one of the menu items open it's link in a new window.

If this was just a link, I'd add a "target='_blank'" attribute and be done. However, a quick romp in the web.sitemap file showed that Visual Studio didn't have anything in the intellisence that resembled the target attribute. So what are we to do? Well, I'm glad you asked.

A little digging showed that the System.Web.UI.WebControls.MenuItem object actually had a target property. So all I had to do was set it. In the Web.Sitemap, I added a target attribute to the sitemap node.

<siteMapNode url="http://ewo/" title="EWO" target="_blank" />


Then I mapped the OnMenuItemDataBound event to a custom handler.



<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" ShowStartingNode="false" />
<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1" Orientation="Horizontal"
OnMenuItemDataBound="Menu1_MenuItemDataBound">


The target attribute that I set in the SiteMapNode is translated into the dataobject and can easily be retrieved and used to set the MenuItem's target property.



protected void Menu1_MenuItemDataBound(object sender, MenuEventArgs e)
{
SiteMapNode node = (SiteMapNode)e.Item.DataItem;

if (node["target"] != null)
e.Item.Target = node["target"];
}


There are other great attributes that can be set this way, including the image url, text and tooltip properties. Have fun!

No comments: