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

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

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

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

最佳答案

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

<%
    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);
}

关于c# - 在 asp.net mvc 中的母版页上有条件地渲染部分,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1749730/

10-11 17:25