views:

433

answers:

2

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?

+4  A: 

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
Yes, I was hoping for something a little more elegant! But I agree this is a work around.
Rippo
Thanks for answer though!
Rippo
@Rippo yeah, I understand. Actually, you might try an extension method. I'll give an example.
Joseph
+1  A: 

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
Is ConditionalRenderPartial a mvc v2 method?
Rippo
@Rippo no, I provide the implementation below but I forgot to rename it from `RenderPartialIfInRole`, which was confusing. Fixed now.
Gabe Moothart
@Gabe, ah I thought so! thanks for edit
Rippo