How do I use MVC role resolution in a view?
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
}
source to share
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>
}
source to share