开发者

Renderpartial conditionally on masterpage in asp.net mvc

Hi I have the following menus defined on my masterp开发者_如何转开发age in a asp.net mvc web application

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

However I want to only display the right menu depending on the logged in users role. How do I achieve this?

I am starting to think that my strategy is incorrect so is there a better method for achieving the same thing?


As a simple example, you could do this:

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

or perhaps your users can be in multiple roles, in which case something like this logic might be more appropriate:

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

Or a more elegant approach for the latter using an extension method:

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

with

public static void RenderPartialIfInRole
    (this HtmlHelper html, string control, string role)
{
    if (HttpContext.Current.User.IsInRole(role)
        html.RenderPartial(control);
}


Extensions methods are the way to go here. More generally than @Joseph's RenderPartialIfInRole, you could use a ConditionalRenderPartial method:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜