How to remove a MenuItem base on condition


There may be an easier solution, which is to use the MenuItemDataBound event. I use this to hide menu nodes from the Menu Controller . Keeping them in the siteMap allows them to appear in the Menu Controller, but I don't want them in the Menu Controller based on the Roles attribute . Here's my code:

The SiteMap File

<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
    <siteMapNode url="" title=""  description="">
        <siteMapNode url="#" title="Home" roles="*"  description="This is Homepage" />
        <siteMapNode url="" title="About" roles="*"  description="This About Page" />
        <siteMapNode url="_#" title="Product" roles="ADMIN" description="This is Product Page, Only Role Admin Can access" />
    </siteMapNode>
</siteMap>

The ASPX Page

<br />
    <asp:Menu ID="NavigationMenu" runat="server" BackColor="#F7F6F3" DataSourceID="SiteMapDataSource1"
        DynamicHorizontalOffset="2" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#7C6F57"
        StaticSubMenuIndent="10px">
        <DynamicHoverStyle BackColor="#7C6F57" ForeColor="White" />
        <DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
        <DynamicMenuStyle BackColor="#F7F6F3" />
        <DynamicSelectedStyle BackColor="#5D7B9D" />
        <StaticHoverStyle BackColor="#7C6F57" ForeColor="White" />
        <StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
        <StaticSelectedStyle BackColor="#5D7B9D" />
    </asp:Menu>
    <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" SiteMapProvider="SitemapSys" />
    <br />


The Code Behind


 protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
NavigationMenu.MenuItemDataBound += new MenuEventHandler(NavigationMenu_MenuItemDataBound);
}
}
void NavigationMenu_MenuItemDataBound(object sender, MenuEventArgs e)
{
SiteMapNode node = (SiteMapNode)e.Item.DataItem;
if (node.Roles.Count > 0)
{
string accessLvl = node.Roles[0].ToString();
string userLogInRoles = "ANONYMOUS";
if ((userLogInRoles .Trim().ToUpper() != accessLvl.Trim().ToUpper()) &&
accessLvl != "*" )
{
e.Item.Parent.ChildItems.Remove(e.Item);
}
}
}

Web.Config

<siteMap>
      <providers>
        <add name="SitemapSys" type="System.Web.XmlSiteMapProvider" siteMapFile="~/Web.sitemap" />
      </providers>
    </siteMap>



By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

Popular posts from this blog

Example to disable save as certain file type in SSRS Report Viewer

How to create DataGrid or GridView in JSP - Servlet

Control Webpart Visible/Enable using macro in Kentico