Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 4 How do you serve different HTML based on Role?

On top of allowing only certain Roles to access certain Controller or Action, I would like to serve a slightly different HTML based on the roles.

Admin can see Edit button for example, meanwhile for other user this edit button will not be there. It can be more complicated than this, for example certain role can edit but can't delete.. etc..

Is there a framework in MVC 4 to do this?

The question here seems interesting, ASP.NET MVC Alternatively Rendering EditorFor Based on User Role

But I am not sure whether this is the proper way to do it.

like image 361
Rosdi Kasim Avatar asked Feb 16 '23 02:02

Rosdi Kasim


1 Answers

For menus, consider using MVCSiteMapProvider, which, like other SiteMapProviders, can be configured to use "security trimming", i.e. to only display nodes that the current user is authorized to use. I.e. a site map can be used to generate a menu which will automatically respect the Authorize attributes on controllers and actions.

For visibility of controls (edit button, delete button and the like), add boolean properties to your Model: CanEdit, CanDelete etc, and have your controller populate them based on the user's roles (User.IsInRole).

Separation of concerns dictates that you shouldn't access Roles directly in the View.

like image 124
Joe Avatar answered Mar 05 '23 19:03

Joe