user9356915
user9356915

Reputation:

Generating menu based on user role Asp.net c#

I have 2 different roles (administrator and regular user); based on the user that was entered only those menus they'll have access to. However, I'm not sure how to get the menu from such. Their roles are stored in a database table. This is what I have so far in the design window.

<asp:Menu ID="Menu1" runat="server" DynamicHoverStyle-BackColor="#99ccff" Orientation="Horizontal" Font-Size="X-Large" ForeColor="#003366" DynamicEnableDefaultPopOutImage="False" ScrollDownImageUrl="~/Img/1.jpg" StaticEnableDefaultPopOutImage="False" >
    <DynamicHoverStyle BackColor="#99CCFF" />
    <Items>
        <asp:MenuItem NavigateUrl="~/Home/Welcome.aspx" Text="Home" Value="Home" ToolTip="Home" ></asp:MenuItem>
        <asp:MenuItem  Text="Search User"  ToolTip="Search"></asp:MenuItem>

        <asp:MenuItem Text="Add User" Value="Add User">

        <asp:MenuItem  NavigateUrl="~/Account/login.aspx" Text="Log Out"  ToolTip="Log Out"></asp:MenuItem> 
    </Items>
</asp:Menu>

Update

if (dr.Read())
{
    if (Convert.ToString(dr["RoleName"]) == "Administrator")
    {
        Menu1.Items.Add(new MenuItem
        {
            NavigateUrl = "~/Home/Welcome.aspx",
            Text = "Home",
        });
    }
}

Upvotes: 0

Views: 1992

Answers (2)

Tim
Tim

Reputation: 4101

  1. Add IDs to your menu items giving them distinct names. Set visible='false' on the admin items
  2. In your codebehind file check if the user is an admin. If so, set visible=true on the admin items.

Depending on your requirement, you could disable them (in which case they'd appear in the menu but not work unless the user was an admin).

Menu item: <asp:MenuItem ID="menu1" visible="false" Text="Add User" Value="Add User">

Codebehind would be along the lines of:

if (user.isAdmin) { menu1.Visible = true }

Upvotes: 1

Mudassar
Mudassar

Reputation: 598

You can use Session. Check if he is admin then show his menu and if he is regular user then show his menu.

if(Session["type"]=="admin")
{
//
}
else if(Session["type"]=="regularUser")
{
//
}

Upvotes: 0

Related Questions