Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Am I able to hide certain menu items in an asp:Menu control based on role?

<asp:Menu ID="mTopMenu" runat="server" Orientation="Horizontal" />
    <Items>
        <asp:MenuItem Text="File">
            <asp:MenuItem Text="New Project" />
            <asp:MenuItem Text="Release Template" NavigateUrl="~/Release/ReleaseTemplate.aspx" />
            <asp:MenuItem Text="Release Schedule" NavigateUrl="~/Release/ReleaseSchedule.aspx" />
            <asp:MenuItem Text="Roles" NavigateUrl="~/Admin/AdminRoles.aspx" />
        </asp:MenuItem>
    </Items>
</asp:Menu>

How can I make one of these items visible to only users in the Admin role? I am using asp.net role provider.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
466 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can remove unwanted menu items in Page_Load, like this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Roles.IsUserInRole("Admin"))
        {
            MenuItemCollection menuItems = mTopMenu.Items;
            MenuItem adminItem = new MenuItem();
            foreach (MenuItem menuItem in menuItems)
            {
                if (menuItem.Text == "Roles")
                    adminItem = menuItem;
            }
            menuItems.Remove(adminItem);
        }
    }

I'm sure there's a neater way to find the right item to remove, but this one works. You could also add all the wanted menu items in a Page_Load method, instead of adding them in the markup.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...