我可以根据角色隐藏/显示 asp:Menu 项吗?

发布于 2024-10-16 21:55:09 字数 676 浏览 1 评论 0原文

我可以根据角色隐藏 asp:Menu 控件中的某些菜单项吗?

<asp:Menu ID="mTopMenu" runat="server" Orientation="Horizontal" />
    <Items>
        <asp:MenuItem Text="File">
            <asp:MenuItem Text="New Project" />
            <asp:MenuItem Text="Release Template" NavigateUrl="~/Release/ReleaseTemplate.aspx" />
            <asp:MenuItem Text="Release Schedule" NavigateUrl="~/Release/ReleaseSchedule.aspx" />
            <asp:MenuItem Text="Roles" NavigateUrl="~/Admin/AdminRoles.aspx" />
        </asp:MenuItem>
    </Items>
</asp:Menu>

如何使这些项目之一仅对管理员角色的用户可见? 我正在使用 asp.net 角色提供程序。

Am I able to hide certain menu items in an asp:Menu control based on role?

<asp:Menu ID="mTopMenu" runat="server" Orientation="Horizontal" />
    <Items>
        <asp:MenuItem Text="File">
            <asp:MenuItem Text="New Project" />
            <asp:MenuItem Text="Release Template" NavigateUrl="~/Release/ReleaseTemplate.aspx" />
            <asp:MenuItem Text="Release Schedule" NavigateUrl="~/Release/ReleaseSchedule.aspx" />
            <asp:MenuItem Text="Roles" NavigateUrl="~/Admin/AdminRoles.aspx" />
        </asp:MenuItem>
    </Items>
</asp:Menu>

How can I make one of these items visible to only users in the Admin role?
I am using asp.net role provider.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

︶ ̄淡然 2024-10-23 21:55:09

您可以在 Page_Load 中删除不需要的菜单项,如下所示:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Roles.IsUserInRole("Admin"))
        {
            MenuItemCollection menuItems = mTopMenu.Items;
            MenuItem adminItem = new MenuItem();
            foreach (MenuItem menuItem in menuItems)
            {
                if (menuItem.Text == "Roles")
                    adminItem = menuItem;
            }
            menuItems.Remove(adminItem);
        }
    }

我确信有一种更简洁的方法可以找到要删除的正确项目,但这个方法有效。您还可以在 Page_Load 方法中添加所有所需的菜单项,而不是在标记中添加它们。

You can remove unwanted menu items in Page_Load, like this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Roles.IsUserInRole("Admin"))
        {
            MenuItemCollection menuItems = mTopMenu.Items;
            MenuItem adminItem = new MenuItem();
            foreach (MenuItem menuItem in menuItems)
            {
                if (menuItem.Text == "Roles")
                    adminItem = menuItem;
            }
            menuItems.Remove(adminItem);
        }
    }

I'm sure there's a neater way to find the right item to remove, but this one works. You could also add all the wanted menu items in a Page_Load method, instead of adding them in the markup.

乖乖 2024-10-23 21:55:09

您可以将菜单项绑定到站点地图并使用角色属性。您需要在 Web.Config 中启用安全调整才能执行此操作。这是最简单的方法。

网站导航概述:
http://msdn.microsoft.com/en-us/library/e468hxky.aspx

安全性修剪信息:
http://msdn.microsoft.com/en-us/library/ms178428.aspx

绑定信息:
http://www.w3schools.com/aspnet/aspnet_navigation.asp

很好的教程/概述:
http://weblogs.asp.net/jgalloway/archive/2008/01/26/asp-net-menu-and-sitemap-security- trimming-plus-a-trick-for-when-your-menu-and-security-don-t-match-up.aspx

另一种有效但不太理想的选项是使用 loginview 控件,可以根据角色显示控件。这可能是最快(但最不灵活/性能)的选项。您可以在此处找到指南:http:// /weblogs.asp.net/sukumarraju/archive/2010/07/28/role-based-authorization-using-loginview-control.aspx

You can bind the menu items to a site map and use the roles attribute. You will need to enable Security Trimming in your Web.Config to do this. This is the simplest way.

Site Navigation Overview:
http://msdn.microsoft.com/en-us/library/e468hxky.aspx

Security Trimming Info:
http://msdn.microsoft.com/en-us/library/ms178428.aspx

SiteMap Binding Info:
http://www.w3schools.com/aspnet/aspnet_navigation.asp

Good Tutorial/Overview here:
http://weblogs.asp.net/jgalloway/archive/2008/01/26/asp-net-menu-and-sitemap-security-trimming-plus-a-trick-for-when-your-menu-and-security-don-t-match-up.aspx

Another option that works, but is less ideal is to use the loginview control which can display controls based on role. This might be the quickest (but least flexible/performant) option. You can find a guide here: http://weblogs.asp.net/sukumarraju/archive/2010/07/28/role-based-authorization-using-loginview-control.aspx

我还不会笑 2024-10-23 21:55:09

我更喜欢使用 FindItem 方法并使用值路径来查找项目。确保菜单上的 PathSeparator 属性与 FindItem 参数中使用的属性相匹配。

    protected void Page_Load(object sender, EventArgs e)
    {

        // remove manage user accounts menu item for non-admin users.
        if (!Page.User.IsInRole("Admin"))
        {
            MenuItem item = NavigationMenu.FindItem("Users/Manage Accounts");
            item.Parent.ChildItems.Remove(item);  
        }

    }

I prefer to use the FindItem method and use the value path for locating the item. Make sure your PathSeparator property on the menu matches what you're using in FindItem parameter.

    protected void Page_Load(object sender, EventArgs e)
    {

        // remove manage user accounts menu item for non-admin users.
        if (!Page.User.IsInRole("Admin"))
        {
            MenuItem item = NavigationMenu.FindItem("Users/Manage Accounts");
            item.Parent.ChildItems.Remove(item);  
        }

    }
梦途 2024-10-23 21:55:09

这最好在 MenuItemDataBound 中完成。

protected void NavigationMenu_MenuItemDataBound(object sender, MenuEventArgs e)
{
    if (!Page.User.IsInRole("Admin"))
    {
        if (e.Item.NavigateUrl.Equals("/admin"))
        {
            if (e.Item.Parent != null)
            {
                MenuItem menu = e.Item.Parent;

                menu.ChildItems.Remove(e.Item);
            }
            else
            {
                Menu menu = (Menu)sender;

                menu.Items.Remove(e.Item);
            }               
        }
    }
}

由于该示例使用 NavigateUrl,因此它不特定于语言,并且适用于具有本地化站点地图的站点。

This is best done in the MenuItemDataBound.

protected void NavigationMenu_MenuItemDataBound(object sender, MenuEventArgs e)
{
    if (!Page.User.IsInRole("Admin"))
    {
        if (e.Item.NavigateUrl.Equals("/admin"))
        {
            if (e.Item.Parent != null)
            {
                MenuItem menu = e.Item.Parent;

                menu.ChildItems.Remove(e.Item);
            }
            else
            {
                Menu menu = (Menu)sender;

                menu.Items.Remove(e.Item);
            }               
        }
    }
}

Because the example used the NavigateUrl it is not language specific and works on sites with localized site maps.

沙与沫 2024-10-23 21:55:09

简单的方法可能并不适合所有情况

        <%                
            if (Session["Utype"].ToString() == "1")
            {
        %>
        <li><a href="../forms/student.aspx"><i class="fa fa-users"></i><span>STUDENT DETAILS</span></a></li>   
        <li><a href="../forms/UserManage.aspx"><i class="fa fa-user-plus"></i><span>USER MANAGEMENT</span></a></li>
        <%
              }
            else
             {
        %>                      
        <li><a href="../forms/Package.aspx"><i class="fa fa-object-group"></i><span>PACKAGE</span></a></li>
        <%
             }                
        %>

SIMPLE method may not be the best for all cases

        <%                
            if (Session["Utype"].ToString() == "1")
            {
        %>
        <li><a href="../forms/student.aspx"><i class="fa fa-users"></i><span>STUDENT DETAILS</span></a></li>   
        <li><a href="../forms/UserManage.aspx"><i class="fa fa-user-plus"></i><span>USER MANAGEMENT</span></a></li>
        <%
              }
            else
             {
        %>                      
        <li><a href="../forms/Package.aspx"><i class="fa fa-object-group"></i><span>PACKAGE</span></a></li>
        <%
             }                
        %>
真心难拥有 2024-10-23 21:55:09

试试这个:

protected void Menu1_DataBound(object sender, EventArgs e)
{
   recursiveMenuVisit(Menu1.Items);
}

private void recursiveMenuVisit(MenuItemCollection items)
        {
            MenuItem[] itemsToRemove = new MenuItem[items.Count];
            int i = 0;

            foreach (MenuItem item in items)
            {
                if (item.NavigateUrl.Contains("Contact.aspx"))
                {
                    itemsToRemove[i] = item;
                    i++;
                }
                else
                {
                    if (item.ChildItems.Count > 0) recursiveMenuVisit(item.ChildItems);
                }
            }

            for(int j=0; j < i; j++)
            {
                items.Remove(itemsToRemove[j]);
            }
        }

Try this:

protected void Menu1_DataBound(object sender, EventArgs e)
{
   recursiveMenuVisit(Menu1.Items);
}

private void recursiveMenuVisit(MenuItemCollection items)
        {
            MenuItem[] itemsToRemove = new MenuItem[items.Count];
            int i = 0;

            foreach (MenuItem item in items)
            {
                if (item.NavigateUrl.Contains("Contact.aspx"))
                {
                    itemsToRemove[i] = item;
                    i++;
                }
                else
                {
                    if (item.ChildItems.Count > 0) recursiveMenuVisit(item.ChildItems);
                }
            }

            for(int j=0; j < i; j++)
            {
                items.Remove(itemsToRemove[j]);
            }
        }
终陌 2024-10-23 21:55:09

我的菜单位于网站母版页中。我使用 Page_Load() 函数使“Admin”菜单项仅对具有管理员角色的用户可见。

using System;
using System.Linq;
using Telerik.Web.UI;
using System.Web.Security;



<telerik:RadMenu ID="menu" runat="server" RenderMode="Auto"  >
    <Items>
       <telerik:RadMenuItem    Text="Admin"  Visible="true" />
    </Items>
 </telerik:RadMenu>

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        RadMenuItem item = this.menu.FindItemByText("Admin");
        if (null != item)
        {
            if (Roles.IsUserInRole("Admin"))
            {
                item.Visible = true;   
            }
            else
            {
                item.Visible = false;
            }
        }
    }
}

I have my menu in the site master page. I used the Page_Load() function to make the "Admin" menu item only visible to users with an Admin role.

using System;
using System.Linq;
using Telerik.Web.UI;
using System.Web.Security;



<telerik:RadMenu ID="menu" runat="server" RenderMode="Auto"  >
    <Items>
       <telerik:RadMenuItem    Text="Admin"  Visible="true" />
    </Items>
 </telerik:RadMenu>

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        RadMenuItem item = this.menu.FindItemByText("Admin");
        if (null != item)
        {
            if (Roles.IsUserInRole("Admin"))
            {
                item.Visible = true;   
            }
            else
            {
                item.Visible = false;
            }
        }
    }
}
长途伴 2024-10-23 21:55:09

:从 ASP.net NavigationMenu 中删除 MenuItem

public static void RemoveMenuItemByValue(MenuItemCollection items, String value)
{
   MenuItem itemToRemove = null;

   //Breadth first, look in the collection
   foreach (MenuItem item in items)
   {
      if (item.Value == value)
      {
          itemToRemove = item;
          break;
      }
   }

   if (itemToRemove != null)
   {
      items.Remove(itemToRemove);
      return;
   }


   //Search children
   foreach (MenuItem item in items)
   {
       RemoveMenuItemByValue(item.ChildItems, value);
   }
}

要通过 Value:和帮助程序扩展

public static RemoveMenuItemByValue(this NavigationMenu menu, String value)
{
   RemoveMenuItemByValue(menu.Items, value);
}

以及示例用法:

navigationMenu.RemoveMenuItemByValue("UnitTests");

注意:任何代码都会发布到公共领域。无需归属。

To remove a MenuItem from an ASP.net NavigationMenu by Value:

public static void RemoveMenuItemByValue(MenuItemCollection items, String value)
{
   MenuItem itemToRemove = null;

   //Breadth first, look in the collection
   foreach (MenuItem item in items)
   {
      if (item.Value == value)
      {
          itemToRemove = item;
          break;
      }
   }

   if (itemToRemove != null)
   {
      items.Remove(itemToRemove);
      return;
   }


   //Search children
   foreach (MenuItem item in items)
   {
       RemoveMenuItemByValue(item.ChildItems, value);
   }
}

and helper extension:

public static RemoveMenuItemByValue(this NavigationMenu menu, String value)
{
   RemoveMenuItemByValue(menu.Items, value);
}

and sample usage:

navigationMenu.RemoveMenuItemByValue("UnitTests");

Note: Any code is released into the public domain. No attribution required.

⒈起吃苦の倖褔 2024-10-23 21:55:09

您只需在页面初始化事件中删除父菜单即可。

    Protected Sub navMenu_Init(sender As Object, e As System.EventArgs) Handles navMenu.Init
    'Remove the admin menu for the norms
    Dim cUser As Boolean = HttpContext.Current.User.IsInRole("Admin")

    'If user is not in the Admin role removes the 1st menu at index 0
    If cUser = False Then
        navMenu.Items.RemoveAt(0)
    End If
End Sub

You just have to remove the parent menu in the page init event.

    Protected Sub navMenu_Init(sender As Object, e As System.EventArgs) Handles navMenu.Init
    'Remove the admin menu for the norms
    Dim cUser As Boolean = HttpContext.Current.User.IsInRole("Admin")

    'If user is not in the Admin role removes the 1st menu at index 0
    If cUser = False Then
        navMenu.Items.RemoveAt(0)
    End If
End Sub
风吹过旳痕迹 2024-10-23 21:55:09

根据角色查找内容页面中的菜单项

 protected void Page_Load(object sender, EventArgs e)
{
   if (Session["AdminSuccess"] != null)
        {
           Menu mainMenu = (Menu)Page.Master.FindControl("NavigationMenu");

    //you must know the index of items to be removed first
    mainMenu.Items.RemoveAt(1);

    //or you try to hide menu and list items inside menu with css 
    // cssclass must be defined in style tag in .aspx page
    mainMenu.CssClass = ".hide";

        }   

}

<style type="text/css">
.hide
    {
        visibility: hidden;
     }
  </style>  

To find menu items in content page base on roles

 protected void Page_Load(object sender, EventArgs e)
{
   if (Session["AdminSuccess"] != null)
        {
           Menu mainMenu = (Menu)Page.Master.FindControl("NavigationMenu");

    //you must know the index of items to be removed first
    mainMenu.Items.RemoveAt(1);

    //or you try to hide menu and list items inside menu with css 
    // cssclass must be defined in style tag in .aspx page
    mainMenu.CssClass = ".hide";

        }   

}

<style type="text/css">
.hide
    {
        visibility: hidden;
     }
  </style>  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文