3

嗨,我在 asp.net mvc Web 应用程序的母版页上定义了以下菜单

<%Html.RenderPartial("AdminMenu"); %>
<%Html.RenderPartial("ApproverMenu"); %>
<%Html.RenderPartial("EditorMenu"); %>

但是,我只想根据登录的用户角色显示正确的菜单。我如何实现这一目标?

我开始认为我的策略不正确,那么有没有更好的方法来实现同样的目标?

4

2 回答 2

8

作为一个简单的例子,你可以这样做:

<% 
    if (User.IsInRole("AdminRole")
        Html.RenderPartial("AdminMenu"); 
    else if (User.IsInRole("Approver")
        Html.RenderPartial("ApproverMenu"); 
    else if (User.IsInRole("Editor")
        Html.RenderPartial("EditorMenu"); 
%>

或者您的用户可能有多个角色,在这种情况下,类似这样的逻辑可能更合适:

<% 
    if (User.IsInRole("AdminRole")
        Html.RenderPartial("AdminMenu"); 
    if (User.IsInRole("Approver")
        Html.RenderPartial("ApproverMenu"); 
    if (User.IsInRole("Editor")
        Html.RenderPartial("EditorMenu"); 
%>

或者使用扩展方法为后者提供更优雅的方法:

<% 
    Html.RenderPartialIfInRole("AdminMenu", "AdminRole"); 
    Html.RenderPartialIfInRole("ApproverMenu", "Approver"); 
    Html.RenderPartialIfInRole("EditorMenu", "Editor"); 
%>

public static void RenderPartialIfInRole
    (this HtmlHelper html, string control, string role)
{
    if (HttpContext.Current.User.IsInRole(role)
        html.RenderPartial(control);
}
于 2009-11-17T15:42:29.760 回答
2

扩展方法是这里的方法。比@Joseph's 更普遍的是RenderPartialIfInRole,您可以使用一种ConditionalRenderPartial方法:

<% 
    Html.ConditionalRenderPartial("AdminMenu", HttpContext.Current.User.IsInRole("AdminRole")); 
    Html.ConditionalRenderPartial("ApproverMenu", HttpContext.Current.User.IsInRole("ApproverRole")); 
    Html.ConditionalRenderPartial("EditorMenu", HttpContext.Current.User.IsInRole("EditorRole")); 
%>

...

public static void ConditionalRenderPartial
    (this HtmlHelper html, string control, bool cond)
{
    if (cond)
        html.RenderPartial(control);
}
于 2009-11-17T15:58:36.803 回答