stats101
stats101

Reputation: 1877

How to show/hide things in the View using role permissions?

I’m using authentication with Active Directory within an ASP .NET MVC3 web application.

I want to control what components are rendered in the view. The option I’m considering is passing in the groups the logged in user is part of from the controller, and then using a helper object to check whether the user is part of the required group. Is this the best method to achieve this? If it is, then how would I achieve the controller part?

Thanks.

Upvotes: 1

Views: 249

Answers (2)

Idrees Khan
Idrees Khan

Reputation: 7752

You can write an extension method. Let's say you want to check whether user is admin or not. So, you do that using extension method like this;

public static class AuthHelper
{
    public static bool IsUserAdmin(this HtmlHelper helper)
    {
        return helper.ViewContext.HttpContext.User.IsInRole("Administrator");
    }
}

i hope this helps.

Upvotes: 0

Jupaol
Jupaol

Reputation: 21355

Well this could be achieved if you use a correct model linked to the page (view-model, not a class from your domain), if you follow this approach, the view model should contain all the information required by the view and nothing more, since your view requires to know which controls should be visible based on the current user roles, I would create a property for each control in the view model like this:

public class MyViewModel
{
   public bool ShowMycontrol1 { get; set; }
}

in your controller populate this "flags" using the current user roles, and finally in the view check for these properties in order to show or hide the required controls

This is just one way to accomplish this, I'm sure there many more

Upvotes: 1

Related Questions