开发者

Render partial view based on condition

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 ?


Use an HTMLHelper

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

Kindness,

Dan


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜