Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render partial view based on condition

Tags:

asp.net-mvc

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 ?

like image 530
sirrocco Avatar asked Feb 16 '26 22:02

sirrocco


1 Answers

Use an HTMLHelper

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

Kindness,

Dan

like image 148
Daniel Elliott Avatar answered Feb 18 '26 12:02

Daniel Elliott