The asp menu control is in the master page. Its datasource is a web.sitemap file. This file has all the items/Pages declared as nodes, initially. I have written this code to remove the items from the menu based on the user permissions, after user logs in.
protected void MyMenu_MenuItemDataBound(object sender, MenuEventArgs e)
{
if(Session["MenuLoaded"]==null)
{
SiteMapNode node = (SiteMapNode)e.Item.DataItem;
bool deleteItem = true;
if(lstRoles.Count==0)
lstRoles = (List<tblDetail>)Session["sRoles"];
if(!string.IsNullOrEmpty(node.Description))
{
foreach(var item in lstRoles)
{
if(Convert.ToInt32(node.Description)==item.FormId)
{
deleteItem = false;
break;
}
}
if(deleteItem)
{
if(e.Item.Parent !=null)
{
MenuItem mItem = e.Item.Parent;
mItem.ChildItems.Remove(e.Item);
if(mItem.ChildItems.Count==0)
{
if(mItem.Parent !=null)
{
MenuItem Item = mItem.Parent;
Item.ChildItems.Remove(mItem);
}
else
{
Menu menu = (Menu)sender;
menu.Items.Remove(mItem);
}
}
else
{
Menu menu = (Menu)sender;
menu.Items.Remove(e.Item);
}
}
}
}
}
}
protected void MyMenu_DataBound(object sender, EventArgs e)
{
Session["MenuLoaded"]=true;
}
The reason for the session variable is - The menuitemdatabound fires for every refresh/page request clicks, and I wanted the menu to be loaded only once for a user session.
PROBLEM:
The 'Remove Item' code works fine. When the user logs in, the menu items do not show as desired. But when he clicks on an existing item to move to another page, All the menus appear again in the menubar.
Why is this happening. Should I allow the menuitemdatabound event everytime a page is refreshed or new url requested. Thats not right.is it?. But any other way around? or i could just remove the session condition.
using C#
TRIED THIS:
page_load()
{
if(Session["sMenuLoaded"]==null)
lstRoles = (List<tblRoles>)Session["sMenuLoaded"];
else
{
Menu mainMenu = (Menu)Session["sMenuLoaded"];
mainMenu.DataBind();
}
}
mymenu_menuitemdatabound()
{
// remains the same as above
}
mymenu_databound()
{
Session["sMenuLoaded"] = (Menu)Page.Master.FindControl("menuBar");
}