Click here to Skip to main content
Click here to Skip to main content

ASP.NET Horizontal Menu Control

, 27 Feb 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
An article on how to put together an ASP.NET horizontal menu control with access key and target window support.


A few weeks ago, I was working on an ASP.NET web application and needed a simple horizontal menu with a submenu. I decided to use the ASP.NET Menu control, and just drag and drop the control on to the page. Simple enough, but the control does not provide access key and target window support on menu items. I have put together a tutorial on how to:

  1. Include an accesskey attribute
  2. Include a target attribute
  3. Include a Site Map Path
Figure 1

Sample results

Getting started

Here is the structure of my project. You are welcome to download the demo.

Figure 2

Project Structure

Putting everything together

First, add a Site Map to the website project. Open the web.sitemap file and populate it with your navigation data and structures. To underline a certain character of the menu title, we can use the HTML underline tag (<u></u>). In order to parse the XML flawlessly, we must replace the less than sign (<) with & lt; (no spaces). Then, include accesskey and target attributes with a value to each siteMapNode. See below for an example.

Site Map

Listing 1
      <siteMapNode url="Default.aspx" 
         title="& lt;u>H& lt;/u>ome" 
         accesskey="H" />
      <siteMapNode url="~/Views/Menu1.aspx" 
                   title="& lt;u>M& lt;/u>enu1"  
                   description="Menu1" accesskey="M" />
        <siteMapNode url="~/Views/Menu2.aspx" 
                     description="Menu2" accesskey="E" />
    <siteMapNode url="~/Views/Menu3.aspx" 
                 accesskey="N" target="_blank" />
    <siteMapNode url="~/Views/Menu4.aspx" 
                 description="Menu4" accesskey="U">
      <siteMapNode url="~/Views/Menu4Sub1.aspx" 
                   accesskey="S" />
      <siteMapNode url="~/Views/Menu4Sub2.aspx" 
                   target="_blank" accesskey="B" />

Master Page

Add a Master Page to the website project. Drag a SiteMapDataSource control on to the page and then the Menu control, and wrap the Menu control inside a div tag. A detailed description of each menu property can be found here. Set staticdisplaylevels ="2" and orientation="Horizontal" to display the menu control in horizontal mode. We can use an inline style sheet, or place the CSS style in an external file. In this tutorial, the CSS style is located in the style.css file. See listing 2.

Listing 2
<asp:SiteMapDataSource id="MenuSource" runat="server" />
<div class="background">
  <asp:menu id="NavigationMenu" CssClass="NavigationMenu"  
        staticdisplaylevels="2" DynamicHorizontalOffset="1"
        staticsubmenuindent="1px" MaximumDynamicDisplayLevels="4"
        runat="server" Height="30px">

        <staticmenuitemstyle ItemSpacing="10" 
        <statichoverstyle CssClass="staticHoverStyle" />
       <StaticSelectedStyle CssClass="staticMenuItemSelectedStyle"/> 
        <DynamicMenuItemStyle CssClass="dynamicMenuItemStyle" />      
        <dynamichoverstyle CssClass="menuItemMouseOver" />
        <DynamicMenuStyle CssClass="menuItem" />
       <DynamicSelectedStyle CssClass="menuItemSelected" />
             <asp:MenuItemBinding DataMember="siteMapNode" 
                    NavigateUrlField="url" TextField="title"  
                    ToolTipField="description" />


Drag a SiteMapPath control on to the page. The purpose of this control is to display a navigation path that shows the user the current page location. See listing 3.

Listing 3
<div id="e">
       <asp:SiteMapPath ID="SiteMapPath1" runat="server" 
            PathSeparator=" >> ">
            <PathSeparatorStyle ForeColor="#5D7B9D" CssClass="currentNodeStyle" />
            <CurrentNodeStyle ForeColor="#333333" CssClass="currentNodeStyle" />
            <NodeStyle ForeColor="#7C6F57"  CssClass="currentNodeStyle"  />
            <RootNodeStyle  ForeColor="#5D7B9D" CssClass="currentNodeStyle"  />

Master Page code-behind

Include the MenuItemDataBound and SiteMapResolve event handlers on the Page_Load event. The purpose of the former event is to insert the target attribute value and create an access key for the menu item before it is rendered or displayed in a Menu control. The latter event is to modify the text displayed by the SiteMapPath control.

Listing 4
NavigationMenu.MenuItemDataBound += 
     new MenuEventHandler(NavigationMenu_MenuItemDataBound);
SiteMap.SiteMapResolve += 
     new SiteMapResolveEventHandler(SiteMap_SiteMapResolve);

Shown below is the implementation of the NavigationMenu_MenuItemDataBound method. The MenuItemDataBound event occurs when a menu item in a Menu control is bound to data. That being said, it will loop through each siteMapNode and look for the accesskey and target attributes. There is a target property associated with the menu item, and we can set its target window with the target attribute value. See listing 5.

Listing 5
void NavigationMenu_MenuItemDataBound(object sender, MenuEventArgs e)
    SiteMapNode node = (SiteMapNode)e.Item.DataItem;
    //set the target of the navigation menu item (blank, self, etc...)
    if (node["target"] != null)
        e.Item.Target = node["target"];
    //create access key button
    if (node["accesskey"] != null)
        CreateAccessKeyButton(node["accesskey"] as string, node.Url);

To get the access key to work, add a Panel control to the master page and a JavaScript function to redirect the webpage to the one that is specified. See below.

Listing 6
<asp:Panel ID="AccessKeyPanel" runat="server" />
<script type="text/javascript">
 function navigateTo(url) {
    window.location = url;

Below is the implementation of the CreateAccessKeyButton method. Create an HtmlButton control dynamically and attach an onclick event to it. Set the style.left property to -2555px to hide the control. A complete list of access keys in different browsers is available here.

Listing 7
//create access key button
void CreateAccessKeyButton(string ak, string url)
    HtmlButton inputBtn = new HtmlButton();
    inputBtn.Style.Add("width", "1px");
    inputBtn.Style.Add("height", "1px");
    inputBtn.Style.Add("position", "absolute");
    inputBtn.Style.Add("left", "-2555px");
    inputBtn.Style.Add("z-index", "-1");
    inputBtn.Attributes.Add("type", "button");
    inputBtn.Attributes.Add("value", "");
    inputBtn.Attributes.Add("accesskey", ak);
    inputBtn.Attributes.Add("onclick", "navigateTo('" + url + "');");


The SiteMap.SiteMapResolve event gets triggered when the CurrentNode property is accessed. It will call the ReplaceNodeText method recursively and replace the HTML underline tag. See listing 8.

Listing 8
SiteMapNode SiteMap_SiteMapResolve(object sender, SiteMapResolveEventArgs e)
   if (SiteMap.CurrentNode != null)
            SiteMapNode currentNode = SiteMap.CurrentNode.Clone(true);
            SiteMapNode tempNode = currentNode;
            tempNode = ReplaceNodeText(tempNode);

            return currentNode;

        return null;

//remove <u></u> tag recursively
internal SiteMapNode ReplaceNodeText(SiteMapNode smn)
    //current node
    if (smn != null && smn.Title.Contains("<u>"))
        smn.Title = smn.Title.Replace("<u>", 
                       "").Replace("</u>", "");

    //parent node
    if (smn.ParentNode != null)
        if (smn.ParentNode.Title.Contains("<u>"))
            SiteMapNode gpn = smn.ParentNode;
            smn.ParentNode.Title = smn.ParentNode.Title.Replace(
              "<u>", "").Replace("</u>", "");
            smn = ReplaceNodeText(gpn);
    return smn;

Using the code

Since the menu is in the Master Page, right click the website project, Add New Item, Web Form, and check the Select Master Page checkbox.

Points of interest

The hover menu appears to not work on mobile devices. To remedy this problem, I included a TreeView control and set its Visible property to false. This control expands its entire node by default. That will take care of the above mentioned problem. In the code-behind, hide the Menu control and show the TreeView control if the requesting browser is a mobile device. See listing 9.

Listing 9
protected void Page_Load(object sender, EventArgs e)
    if (Request.Browser.IsMobileDevice)
        NavigationMenu.Visible = false;
        NavigationTreeView.Visible = true;

When I tested the menu on IE 8, the hover menu did not render correctly. To overcome this problem, I set the DynamicMenuStyle z-index to 200, see style.css. The submenu does not work with Google Chrome. After some research, I found the solution for it. See listing 10.

Listing 10
protected void Page_Load(object sender, EventArgs e)
    if (Request.UserAgent.IndexOf("AppleWebKit") > 0)
        NavigationMenu.DynamicMenuStyle.Width = Unit.Pixel(120);

New update

I have received several complaints from readers concerning the menu control not displaying correctly on Safari and Google Chrome browsers. Somehow, the menu items are stacked on each other and the submenu widths are gapped apart. After doing some research, I found the answer here, see listing 11. To fix the submenu width, remove display:block from dynamicMenuItemStyle in the CSS file.

Listing 11
protected override void AddedControl(Control control, int index)
    if (Request.ServerVariables["http_user_agent"].IndexOf("Safari",
        StringComparison.CurrentCultureIgnoreCase) != -1)
        this.Page.ClientTarget = "uplevel";

    base.AddedControl(control, index);

I also rewrote the logic to detect mobile browsers with the code from Vincent Van Zyl. See listing 12.

Listing 12
public static readonly string[] mobiles =
                "midp", "j2me", "avant", "docomo", 
                "novarra", "palmos", "palmsource", 
                "240x320", "opwv", "chtml",
                "pda", "windows ce", "mmp/", 
                "blackberry", "mib/", "symbian", 
                "wireless", "nokia", "hand", "mobi",
                "phone", "cdm", "up.b", "audio", 
                "SIE-", "SEC-", "samsung", "HTC", 
                "mot-", "mitsu", "sagem", "sony"
                , "alcatel", "lg", "eric", "vx", 
                "NEC", "philips", "mmm", "xx", 
                "panasonic", "sharp", "wap", "sch",
                "rover", "pocket", "benq", "java", 
                "pt", "pg", "vox", "amoi", 
                "bird", "compal", "kg", "voda",
                "sany", "kdd", "dbt", "sendo", 
                "sgh", "gradi", "jb", "dddi", 
                "moto", "iphone"

public static bool isMobileBrowser()
    HttpContext context = HttpContext.Current;

    if (context.Request.Browser.IsMobileDevice)
        return true;
    if (context.Request.ServerVariables["HTTP_X_WAP_PROFILE"] != null)
        return true;
    if (context.Request.ServerVariables["HTTP_ACCEPT"] != null &&
        return true;
    if (context.Request.ServerVariables["HTTP_USER_AGENT"] != null)
        for (int i = 0; i < mobiles.Length; i++)
            if (context.Request.ServerVariables["HTTP_USER_AGENT"].
                return true;

    return false;


If you find any bugs or disagree with the contents, please drop me a line and I'll work with you to correct it.

Tested on IE 6.0/7.0/8.0, Google Chrome, Safari, and Firefox.


  • 02/25/2010 - Removed PathSeparator of SiteMapPath before the root node, as suggested by The Code Project member, kentex2000. Added SiteMap.CurrentNode != null to the SiteMap_SiteMapResolve method.
  • 02/03/2010 - Fixed the menu display problem in Safari and Google Chrome browsers, added new logic to detect mobile browsers.



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Bryian Tan
Software Developer
United States United States
I have over three years of experience working with Microsoft technologies. I have earned my Microsoft Certified Technology Specialist (MCTS) certification. I'm a highly motivated self-starter with an aptitude for learning new skills quickly.

Comments and Discussions

QuestionTwo Web.sitemap on the same solution PinmemberMember 470231210-Nov-14 12:48 
QuestionREG:Hover Menu Control PinmemberMember 1067595917-Mar-14 1:04 
QuestionLeading Separator Before Root Node PinmemberMember 81920506-Dec-13 4:59 
Questionhelp me fix this error tks, Pinmemberitlinh11-May-13 1:11 
AnswerRe: help me fix this error tks, PinmemberBryian Tan12-May-13 13:22 
GeneralRe: help me fix this error tks, Pinmemberitlinh16-May-13 9:03 
QuestionMouseover Tabs Menu PinmemberMS Babu10-May-13 21:12 
Hello Bryian,
Please help to convert 2 level asp menu like[^]
MS Babu
QuestionContent for page: Default.aspx PinmemberPowerplanner13-Feb-13 10:09 
AnswerRe: Content for page: Default.aspx PinmemberBryian Tan19-Feb-13 15:50 
Questionabout this article Pinmembershenbagam126-Jan-13 23:28 
AnswerRe: about this article PinmemberBryian Tan19-Feb-13 15:52 
QuestionNice Article... PinmemberTripati Balaji16-Nov-12 1:17 
GeneralRe: Nice Article... PinmemberBryian Tan19-Feb-13 15:53 
Questionthanks PinmemberabiFarrah15-Oct-12 17:07 
GeneralRe: thanks PinmemberBryian Tan19-Feb-13 15:54 
GeneralMy vote of 5 PinmemberMember 93931171-Oct-12 21:34 
GeneralRe: My vote of 5 PinmemberBryian Tan11-Dec-12 5:06 
GeneralHow do you hide submenu items in MaterPage from Content Page? [modified] Pinmemberavt2k617-Jul-12 9:11 
GeneralRe: How do you hide submenu items in MaterPage from Content Page? PinmemberBryian Tan17-Jul-12 15:29 
GeneralRe: How do you hide submenu items in MaterPage from Content Page? Pinmemberavt2k617-Jul-12 16:29 
GeneralRe: How do you hide submenu items in MaterPage from Content Page? PinmemberBryian Tan17-Jul-12 17:36 
SuggestionRe: How do you hide submenu items in MaterPage from Content Page? PinmemberBryian Tan17-Jul-12 17:43 
GeneralRe: How do you hide submenu items in MaterPage from Content Page? [modified] Pinmemberavt2k618-Jul-12 4:40 
GeneralRe: How do you hide submenu items in MaterPage from Content Page? PinmemberBryian Tan19-Jul-12 6:29 
GeneralRe: How do you hide submenu items in MaterPage from Content Page? [modified] Pinmemberavt2k619-Jul-12 9:29 
QuestionObject reference not set to an instance of an object after integrate with authentication mode Pinmemberwong0630214-May-12 22:58 
AnswerRe: Object reference not set to an instance of an object after integrate with authentication mode PinmemberBryian Tan16-May-12 18:45 
Questionneed Pinmembermbsaravanan29-Feb-12 21:37 
Questioncan we generate menu items dynamicaly? PinmemberPankaja Kanavi11-Jan-12 3:20 
SuggestionRe: can we generate menu items dynamicaly? PinmemberBryian Tan29-Jan-12 17:03 
Generalnice Pinmembershaheen_mix17-Dec-11 0:44 
QuestionHow to remove text "Content for page:...." which shows in all pages PinmemberMember 433521327-Aug-11 22:52 
AnswerRe: How to remove text "Content for page:...." which shows in all pages PinmemberBryian Tan28-Aug-11 13:46 
GeneralHiding Menu items Pinmemberbytelinkikr20-Apr-11 9:40 
GeneralVB.NET version. Pinmemberatiqjaved10-Dec-10 5:47 
GeneralRe: VB.NET version. PinmemberBryian Tan11-Apr-11 17:26 
GeneralMy vote of 5 Pinmembermwdoty30-Nov-10 13:13 
QuestionHow to handle variable length dynamic menus in Safari Chrome. Pinmembermwdoty30-Nov-10 13:12 
AnswerRe: How to handle variable length dynamic menus in Safari Chrome. PinmemberBryian Tan30-Nov-10 17:44 
GeneralFantastic component PinmemberXuSCo22-Sep-10 23:04 
GeneralRe: Fantastic component PinmemberBryian Tan23-Sep-10 8:49 
GeneralExpand the menu Pinmemberphamtasmic10-Mar-10 9:51 
GeneralRemove Pathseperator before the Root Node PinmemberVinod SE16-Feb-10 4:43 
GeneralRe: Remove Pathseperator before the Root Node PinmemberBryian Tan16-Feb-10 11:19 
GeneralThe Image Pinmemberkentex20009-Jan-10 18:39 
GeneralRe: The Image PinmemberBryian Tan10-Jan-10 18:22 
GeneralThe Image Pinmemberkentex20008-Jan-10 20:05 
GeneralRe: The Image PinmemberBryian Tan8-Jan-10 21:02 
Questioncan this Menu be bound to a database Pinmemberjarajeshwaran21-Dec-09 20:47 
AnswerRe: can this Menu be bound to a database PinmemberBryian Tan22-Dec-09 12:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150224.1 | Last Updated 27 Feb 2010
Article Copyright 2009 by Bryian Tan
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid