简体   繁体   English

根据用户角色Asp.net C#生成菜单

[英]Generating menu based on user role Asp.net c#

I have 2 different roles (administrator and regular user); 我有2个不同的角色(管理员和普通用户); 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",
        });
    }
}
  1. Add IDs to your menu items giving them distinct names. 将ID添加到菜单项中,为其赋予不同的名称。 Set visible='false' on the admin items 在管理项目上设置visible='false'
  2. In your codebehind file check if the user is an admin. 在您的代码隐藏文件中,检查用户是否是管理员。 If so, set visible=true on the admin items. 如果是这样,请在管理项目上设置visible=true

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"> 菜单项: <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 }

You can use Session . 您可以使用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")
{
//
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM