1

I have one ASP Menu in which it has some menu items. See below code:

<asp:Menu ID="NavigationMenu" runat="server" CssClass="menu"
    EnableViewState="false" IncludeStyleBlock="false"
    Orientation="Horizontal">
                        <Items>
          <asp:MenuItem NavigateUrl="~/Home.aspx" Text="Home"/>
          <asp:MenuItem NavigateUrl="~/AboutUs.aspx" Text="About"/>
          <asp:MenuItem NavigateUrl="~/Admin.aspx" Text="Admin"/>
          <asp:MenuItem NavigateUrl="~/UserAccount.aspx" Text="User"/> 
                        </Items>
                    </asp:Menu>

I want to hide or disable third menu item based on login session. I know how to handle session but I am not right with how to hide one asp:menu item. I can't apply CSS to single Menu Item. So lease tell me what to do.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Guna
  • 21
  • 3

3 Answers3

0

If it was the Admin area you wanted to hide you could use jquery after page loads:

    $('asp:MenutItem[Text="Admin"]').hide();             

    //note you will need to replace selector with generated html
    //something like
    $('#NavigationMenu a[title="Admin"]').hide(); 

Better would be to limit the list on the server side if you can so the limited menu is fixed there, something like this:

        if (!Roles.IsUserInRole("Admin"))
        {
            MenuItemCollection menuItems = NavigationMenu.Items;
            MenuItem adminItem = new MenuItem();
            foreach (MenuItem menuItem in menuItems)
            {
                if (menuItem.Text == "Admin")
                    adminItem = menuItem;
            }
            menuItems.Remove(adminItem);
        }
dove
  • 20,469
  • 14
  • 82
  • 108
0

Why do you want to use javascript? It runs on the rendered html by the asp.net framework where you won't have access to the session.

This question is probably what you are looking for : Can I hide/show asp:Menu items based on role?

Community
  • 1
  • 1
Peter
  • 14,221
  • 15
  • 70
  • 110
0

"How can I hide or disable asp menu item using javascript"

If you do need to use JavaScript, here's some code to do it:

//  Hide one of the top-level ASP.Net menu items

var menuItemToHide = "Rating";

var menuItems = $(".AspNet-Menu-Horizontal > ul > li > a");
$.each(menuItems, function () {
    var menuText = $(this).text().trim();
    if (menuText == menuItemToHide) {
        $(this).parent().hide();
    }  
});

(We have an ASP.Net app where the user's role doesn't come from Active Directory, so I couldn't just stick something into Web.sitemap or web.config. This code uses JQuery to iterate through the top-level menu items in my ASP.Net asp:Menu control, and removes the "Rating" menu.)

Mike Gledhill
  • 27,846
  • 7
  • 149
  • 159