Home > ASP.Net > SiteMap menu with icons

SiteMap menu with icons

While binding a Menu (or TreeView: everything in this article applies to TreeView as well) to a SiteMapDataSource is very easy, it can prove challenging to find how to extend the site map with custom properties and use these extended properties in a Menu. This sample shows how to add icons in a sitemap-driven menu.

SiteMap allows the addition of custom attributes to your site map nodes. If you’re using the XML site map provider, it’s as simple as this:

in Web.SiteMap

<siteMapNode url="default.aspx" title="Home"  description="The home page" imageUrl="images/home.gif">

Here, imageUrl is a custom property, not defined by the SiteMap infrastructure by default.

The first idea that comes to mind to use these custom attributes is to just replace the automatic bindings you get from binding a Menu to SiteMapDataSource with “manual” bindings. This works very well with XmlDataSource because it is implemented so that the nodes implement ICustomTypeDescriptor, so any XML attribute is exposed as a property on the node as far as reflection is concerned. This is a very powerful feature of .NET reflection that gives it some of the qualities of dynamic languages. Unfortunately, SiteMapDataSource does not implement this, nor does Menu know how to query custom site map attributes. This is an oversight and we may add that support in future releases.

An easy (although not declarative) way out of this problem is to hook the OnMenuItemDataBound event and to set the custom properties from there:

with Menu Control

public void Menu1_OnMenuItemBound(object sender, MenuEventArgs args)
    args.Item.ImageUrl = ((SiteMapNode)args.Item.DataItem)["imageUrl"];

with TreeView control

protected void TreeView1_TreeNodeDataBound(object sender, TreeNodeEventArgs e)
   SiteMapNode nodeFromSiteMap = (SiteMapNode)e.Node.DataItem;
   e.Node.ImageUrl = nodeFromSiteMap["ImageUrl"];

I hope this helps.

Good Luck

Categories: ASP.Net Tags: , ,
  1. March 7, 2013 at 7:04 pm

    It’s in point of fact a nice and helpful piece of info. I am happy that you shared this useful information with us. Please keep us up to date like this. Thanks for sharing.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: