ASP.NET MVC3 view authorization design

Imagine that you have a secure site and view that can be generated in several ways, depending on the role of the user. Let's say the administrator sees everything, the Manager sees several columns and some action buttons, the user sees other columns and other action buttons.

How would you implement this? As far as I can see, there are three main options:

  • A controller with the [Authorize] attribute and an action that returns 1 View the user role, which is the view tailored for this role;
  • A controller with the [Authorize] attribute and an action that returns 1 View all roles, with logic to hide / show columns, fields, buttons;
  • A controller with the [Authorize] attribute and an action that returns 1 A view that displays different partial views based on roles.

I prefer the third approach, but do you see a better way to implement this?

Thank you in advance

+4
source share
2 answers

Depending on the complexity of your presentation, the first or third option will seem convenient to me. Regarding the second option; In general, it is recommended to avoid logic in the views, so I would stay away from this.

If you come to the third option, you should consider using EditorTemplates and DisplayTemplates. This will allow you to make your (main) view an agnostic of a partial view of rendering. Make your viewmodel (or part of it) inherit from one base class. Create display and / or editor templates for each type of view model and, in your opinion, just say Html.DisplayFor( ... ) or Html.EditorFor( ... ) . MVC will automatically select the correct template, without the need for logic in your view.

+2
source

What I did for the menu and other navigational elements is that I have a ViewModel class. Here is a simplified version.

ViewModel

 public class Action { public string DisplayName { get; set; } // localized public string Url { get; set; } public class MenuViewModel { public List<Action> Actions { get; set; } public MenuViewModel() { this.Actions = new List<Action>(); } } 

I fill this out depending on the role of the user. Admin gets more links, etc.

This ViewModel is part of the "core" view model.

 public class AlbumEditorViewModel { public MenuViewModel Menu { get; set; } } 

Then I will pass this view model for a partial view that is responsible for the menu.

Preview (Razor)

 @model AlbumEditorViewModel .. razor stuff here .. @Html.Partial("Menu", Model.Navigation) .. razor stuff here .. 

Partial view

 @model MenuViewModel <ul> @foreach (var action in Model.Actions) { <li> @GridHelper.GetAction(action) </li> } </ul> 

I hope this gives you ideas.

0
source

Source: https://habr.com/ru/post/1397794/


All Articles