Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I hide/show asp:Menu items based on role?

Tags:

asp.net

roles

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.

like image 682
kacalapy Avatar asked Feb 08 '11 22:02

kacalapy


2 Answers

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.

like image 91
Jon Hallin Avatar answered Oct 02 '22 16:10

Jon Hallin


You can bind the menu items to a site map and use the roles attribute. You will need to enable Security Trimming in your Web.Config to do this. This is the simplest way.

Site Navigation Overview: http://msdn.microsoft.com/en-us/library/e468hxky.aspx

Security Trimming Info: http://msdn.microsoft.com/en-us/library/ms178428.aspx

SiteMap Binding Info: http://www.w3schools.com/aspnet/aspnet_navigation.asp

Good Tutorial/Overview here: http://weblogs.asp.net/jgalloway/archive/2008/01/26/asp-net-menu-and-sitemap-security-trimming-plus-a-trick-for-when-your-menu-and-security-don-t-match-up.aspx

Another option that works, but is less ideal is to use the loginview control which can display controls based on role. This might be the quickest (but least flexible/performant) option. You can find a guide here: http://weblogs.asp.net/sukumarraju/archive/2010/07/28/role-based-authorization-using-loginview-control.aspx

like image 41
theChrisKent Avatar answered Oct 02 '22 17:10

theChrisKent