Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use an MVC Role permission 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 a Create Article button for a role Editor and hide it for a role Reader?

like image 754
Patrick Avatar asked Nov 25 '25 20:11

Patrick


2 Answers

Its best practice to get the Controller to set a property on the ViewModel, then the View can check for this and it also makes the logic more easily testable.

Its the Models job is to be the communicator with the View.
Then security logic doesn't leak into the View.

In your controller you could do something like:

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

Then if you view you could do the following:

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

@if (model.IsReader)
{
  // show reader button
}
like image 70
Ralph Willgoss Avatar answered Nov 28 '25 10:11

Ralph Willgoss


There are two schools of thought on this.

One school says that you create separate views for roles. So 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 "on the fly" rendering based on role, then you follow an approach more like Ralph suggests. 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 view, 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>
}   
like image 35
Erik Funkenbusch Avatar answered Nov 28 '25 09:11

Erik Funkenbusch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!