Friday, 8 March 2013

show/hide css menu item depending user role using asp.net


You can put this in the Page_Load..
    Dim cs As ClientScriptManager = Page.ClientScript

    If Not cs.IsClientScriptBlockRegistered(Me.GetType(), "RoleVariable") Then
        Dim js As New String
        js = "var _role = " & role & ";"
        cs.RegisterStartupScript(Me.GetType(), "RoleVariable", js, True)
    End If
And from there, you will have the role in the Javascript realm, where you can manipulate the visibility of the items you want.
So...
<script type="text/javascript">
    function hideStuff() {
        if (_role === "operator") {
            // hide/show your elements here
        }
        else if (_role === "guest") {
            // hide/show your elements here
        }
    }
</script>
Keep in mind that this approach is all client-side and is therefore easy for another developer to manipulate if theyreally wanted to. But on the other hand, it's the simplest. Don't use this approach for high-security situations.


Consider catching the MenuItemDataBound event and then using whatever logic you choose to make it Show or hide.
Try below code, hope it helps.
protected void Menu1_MenuItemDataBound(object sender, MenuEventArgs e)
    {
        System.Web.UI.WebControls.Menu menu = (System.Web.UI.WebControls.Menu)sender;
        SiteMapNode mapNode = (SiteMapNode)e.Item.DataItem;


        System.Web.UI.WebControls.MenuItem itemToRemove = menu.FindItem(mapNode.Title);


        if (mapNode.Title == "Node")
        {
            System.Web.UI.WebControls.MenuItem parent = e.Item.Parent;
            if (parent != null)
            {
                parent.ChildItems.Remove(e.Item);
            }
        }
    }

No comments:

Post a Comment