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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With