0

I have a list of asp.net menu items:

<asp:Menu ID="Menu1" runat="server"  OnLoad="Menu1_Load">
    <Items>
        <asp:MenuItem Text="Create Member" Value="Create Member" NavigateUrl="~/create-member.aspx"></asp:MenuItem>
        <asp:MenuItem Text="Edit Member" Value="Edit Member" NavigateUrl="~/edit-member.aspx"></asp:MenuItem>
        <asp:MenuItem Text="Result Export" Value="Result Export" NavigateUrl="~/result-export.aspx"></asp:MenuItem>
        ...
        ...
    </Items>
</asp:Menu>

How can I highlight and remove hyperlink for the currently selected MenuItem?

This is the modified version of Josh's answer (we don't need to set the navigateUrl):

        foreach (MenuItem menuItem in Menu1.Items)
        {
            if (Request.PhysicalPath == Server.MapPath(menuItem.NavigateUrl))
            {
                menuItem.Selected = true;
                menuItem.Selectable = false;
                break;
            }
        }

1 Answer 1

2

If you are looking to do this server-side based on the page being visited, you'll just need to make that evaluation, then find the related item and set the NavigateUrl property to "". Depending on your CSS settings you might also need to assign a specific class to modify the appearance and give the user some visual feedback of their location.

Edit
Probably the best way to do this is to use your Menu1_Load event to test the page URL against the NavigateUrl. If there's a match, remove the NavigateUrl setting. If you weren't using the ~ to establish the root, I might use:

foreach (var menuItem in Menu1.Items)  
{  
    if (Request.Path == menuItem.NavigateUrl)
    {
        menuItem.NavigateUrl = "";
        // Add any CSS modifications here
        break;
    }
}

To be absolutely sure, you could compare the physical paths:

foreach (var menuItem in Menu1.Items)  
{  
    if (Request.PhysicalPath == Server.MapPath(menuItem.NavigateUrl))
    {
        menuItem.NavigateUrl = "";
        // Add any CSS modifications here
        break;
    }
}
5
  • Do you have any sample code? How can I make the evaluation? If I set the NavigateUrl to "", how can I set it back when selecting another item?
    – Billy
    Commented Jan 15, 2010 at 16:12
  • Quick question - is this menu in a master page? Commented Jan 15, 2010 at 16:24
  • Yes, this menu is in a master page.
    – Billy
    Commented Jan 15, 2010 at 16:26
  • I use the method of comparing the physical paths. First, the menuItem with NavigateUrl set to "" will still cause postback. Second, there is no option like menuItem.CssClass to set the css style.
    – Billy
    Commented Jan 17, 2010 at 11:36
  • 1
    I know how to solve the above 2 issues. For the postback problem, set the menuItem.selectable=false. For setting Css style, set the menuItem.selected = true and the staticSelectedStyle.
    – Billy
    Commented Jan 17, 2010 at 12:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.