3

Hi I have the following menus defined on my masterpage 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?

Jason Berkan
  • 8,734
  • 7
  • 29
  • 39
Rippo
  • 22,117
  • 14
  • 78
  • 117

2 Answers2

8

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);
}
Joseph
  • 25,330
  • 8
  • 76
  • 125
  • Yes, I was hoping for something a little more elegant! But I agree this is a work around. – Rippo Nov 17 '09 at 15:43
  • 1
    @Rippo yeah, I understand. Actually, you might try an extension method. I'll give an example. – Joseph Nov 17 '09 at 15:45
2

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);
}
Gabe Moothart
  • 31,211
  • 14
  • 77
  • 99