tags:

views:

182

answers:

2

I have a few partial views that should render when the user has a certain Role.

Now, I want to avoid doing something like

<% if(user is in role){..here goes the html.. }%>

I would like to be able to do (at the top of the ascx) :

<% this.RenderOnlyForRoles(list of roles) %>

Now, in the BasePartialView I have a list of roles that gets populated when RenderOnlyForRoles is called.

The problem is that the RenderOnlyForRoles is called after .. all events I can think of :) and I can't stop the rendering of the control.

Any ideas on how to obtain what I want ?

EDIT: Anyone knows if other viewengines might support this ?

+4  A: 

Use an HTMLHelper

public static void RenderOnlyForRoles(this HtmlHelper html, List<string> roles))
{
    if (check if user in roles)
    {
        html.RenderPartial(yourview);
    }
}

Kindness,

Dan

Daniel Elliott
Wanted to post the same. But that's not what he actually tries to achieve. He wants to explicitly delegate checking of roles responsibility to partial view.
Arnis L.
Ah okay, but that logic should be in controller should it not then? Perhaps an attribute for relevant action methods?
Daniel Elliott
Well... this is a Partial View , so I don't what exactly should I check in the Controller ?. I mean I have a view , with 3 Partial Views. Only one Partial view should be displayed at any time.
sirrocco
In your controller,I would check which views are to be rendered and send that in the ViewModel or view data. Kindness, Dan
Daniel Elliott
I would recommend you do the simplest thing that could work - which in this case is to use an HTML helper. It's code - you can always change it at a later stage.
Jaco Pretorius
A: 

I would be inclined to solve this type of challenge by using polymorphism. In this case you could have a base View you want to render.

When the user is in the desired role, you render the concrete View; otherwise, you can render a Null View that basically does nothing.

Until ASP.NET MVC 2 you will need to map polymorphic Views by hand, but I recently wrote a blog post that describes how you can do that.

Mark Seemann
Sorry I think this is seriously over-engineering the solution. I would recommend you do the simplest thing that could work in this scenario - which is probably to use an HTML helper.
Jaco Pretorius