<asp:Menu ID="mnu" runat="server" PathSeparator="," CssClass="menu" DynamicMenuItemStyle-CssClass="menu">
<Items>
<asp:MenuItem Text="home" NavigateUrl="~/Default.aspx" />
<asp:MenuItem Text="Aboutus" NavigateUrl="#"/>
<asp:MenuItem Text="Support" NavigateUrl="#" />
</Items>
</asp:Menu>
I have this menu in master page, When the user logs into the website, based on the user role I want to add items to the menu from the server side. How can I do that.
Admin(menu to add --> Organisation, Message, Group) Users(menu to add --> Message, Group)
Since I have 6 roles I have different menu item for each role. How can this be done
In the Page_Load
of the master you could check whether the user is in some roles and dynamically add values to the menu:
protected void Page_Load(object sender, EventArgs e)
{
if (User.IsInRole("admin"))
{
mnu.Items.Add(new MenuItem
{
Text = "Administer web site",
NavigateUrl = "~/admin.aspx"
});
}
}
I'd generally use a site map and security trimming. Each siteMapNode has a "roles" attribute that indicates which roles are allowed to see the link in the menu. * is used for all roles or you can enter a comma separated list of roles. e.g.
<?xml version="1.0" encoding="utf-8" ?>
<siteMap>
<siteMapNode title="Home" description="Home"
url="~/default.aspx" roles="*" >
</siteMapNode>
<siteMapNode title="Organization" description="Organization"
url="~/Organization.aspx" roles="Admin" >
</siteMapNode>
<siteMapNode title="Message" description="Message"
url="~/Organization.aspx" roles="Admin, User" >
</siteMapNode>
</siteMap>
etc.
Then you can enable security trimming in your web.config:
<siteMap defaultProvider="XmlSiteMapProvider" enabled="true">
<providers>
<add name="XmlSiteMapProvider"
description="Default Site Map Provider"
type="System.Web.XmlSiteMapProvider"
siteMapFile="Web.sitemap"
securityTrimmingEnabled="true" />
</providers>
</siteMap>
All you have to do then is set the datasource of your asp menu to the site map. More information can be found here: http://msdn.microsoft.com/en-us/library/305w735z.aspx and here: http://msdn.microsoft.com/en-us/library/ms178429(v=vs.80).aspx
I like this approach because adding a new role based menu item is much easier. You don't have to manually check the role in the code behind which will probably end up as an unwieldy if statement anyway.
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