I am a new ASP.NET Web Forms developer and I am struggling now in hiding and showing ASP.NET Menu Control Items based on the user role. The roles are defined by me in the database and based on the result of checking the role of the user, the system should show or hide some of the menu items.
I have the following ASP.NET Menu Control in the Master Page:
<asp:Menu ID="Menu" runat="server" PathSeparator="," Orientation="Horizontal" EnableViewState="false">
<Items>
<asp:MenuItem Text="Home" NavigateUrl="~/Pages/Default.aspx" Value="home"></asp:MenuItem>
<asp:MenuItem Text="Sheet" NavigateUrl="~/Pages/Sheet.aspx" Value="sheet"></asp:MenuItem>
<asp:MenuItem Text="Test" NavigateUrl="~/Pages/Test.aspx" Value="test"></asp:MenuItem>
</Items>
</asp:Menu>
And in the code-behind of the master page I am doing the following logic:
protected void MenuAccess()
{
if(Acccess.HasAccess(username))
{
if(Access.IsAdmin(username))
{
SetMenuItemUrl("sheet", "~/Pages/Sheet.aspx?UserId=");
HideMenuItem("test");
}
if(Access.IsSupport(username))
{
SetMenuItem("test");
}
}
}
protected void HideMenuItem(string valuePath)
{
SetMenuItem(valuePath, false, null);
}
protected void SetMenuItemUrl(string valuePath, string url)
{
SetMenuItem(valuePath, true, url);
}
protected void SetMenuItem(string valuePath, bool visible, string url)
{
var item = Menu.FindItem(valuePath);
if (item != null)
{
if (url != null)
item.NavigateUrl = url;
if (visible == false)
{
if (valuePath.LastIndexOf(',') < 0)
Menu.Items.Remove(item);
else
{
MenuItem parent = Menu.FindItem(valuePath.Substring(0, valuePath.LastIndexOf(',')));
parent.ChildItems.Remove(item);
}
}
}
}
However, if the user has two roles: admin and support, then the menu item with 'test' value will not be displayed and I don't know why. Could you please help me with this?