How do I use MVC role resolution in a view?

How can I apply permission in a view based on a set of users in a role.

For example, how can I show the Create Article button for the role editor and hide it for the Reader role?

+3


source to share


2 answers


The best practice is to force the controller to set a property on the ViewModel, then the View can check this and also make the logic more easily testable.

His modeling job is to be a communicator with performance.
Then the security logic does not leak into the view.

In your controller, you can do something like:



model.IsEditor = User.IsInRole("editor")
model.IsReader = User.IsInRole("reader")

      

Then, if you take a look, you can do the following:

@if (model.IsEditor)
{
  // show editor button
}

@if (model.IsReader)
{
  // show reader button
}

      

+7


source


There are two schools of thought on this.

One school says that you create separate views for roles. This way you create a RoleEditor view and a RoleReader view. And in relatively simple applications, this is probably the best approach.

If your views are more complex and require role-based on-the-fly rendering, then you are taking a more Ralph-like approach. You do something like this:



public ActionResult Index() {
    // IsUserAnEditor is a placeholder for a method to determine whether the user
    // is an editor based on whatever role technology you're using.
    MyModel model = new MyModel { IsEditor = IsUserAnEditor() }
    return View(model);
}

      

Then, in your opinion, you have code like this:

@model MyModel

....

@if(Model.IsEditor)
{
    // Code to add the "Edit" link, this is just an example, customize for your needs
    <span>
    @Html.ActionLink("Edit", "Edit", "MyController", new { id=Model.ID })
    </span>
}   

      

+4


source







All Articles