Alex Kovanev
Alex Kovanev

Reputation: 1888

Checking permissions in controller and in view

I want to create permissions on some actions like creating or updating information (but not for displaying). For this I'm adding attributes before all the necessary methods e.g.

[Permissions(Permissions.Admin)]
public ActionResult Create()
{
   //...
}

Besides I wouldn't like to leave the links active on the index page. So I have to add some checks inside the views.

@if (checking...)
{
    @Html.ActionLink("Create New", "Create")  

}

The more checks I add, the more boring, and the more things I have to keep in my mind. How to do it right?

Upvotes: 2

Views: 964

Answers (3)

StanK
StanK

Reputation: 4770

Your could create a HtmlHelper for this.

Something like @Html.ActionLinkUsingPermissions("Create New", "Create",Permissions.Admin)

The HtmlHelper would decide whether or not to display the link depending on the current users permissions.

Upvotes: 3

Matthew Manela
Matthew Manela

Reputation: 16752

You could also create two different view models. One for read/write and one for just read. Then using the View Templates feature you can have one view automatically pick the right template to show using this line:

@Html.DisplayForModel()

Upvotes: 1

Stéphane Bebrone
Stéphane Bebrone

Reputation: 2763

You can create a read-only version of views and letting the controller decides which version it should return (based on your permission).

Shared UI can be then externalized in partial views.

It's recommended to keep your view free from business logic as much as possible.

Upvotes: 2

Related Questions