Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a view that has different displays according to the role the user is in?

I want to create a view that has different displays according to the role the user is in.

Should I create a different view for different roles or should I check the roles on the Veiw page itself rather than in the actions?

How would I check the role on the view page?

like image 800
devforall Avatar asked Jan 03 '09 15:01

devforall


3 Answers

Or should i use check the roles on the Veiw page its self rather than on actions, if so can someone plz show me how do check that on view page

You need to do both. Check roles on actions as a security measure and check roles on views to enable/disable specific controls.

Within your view page the long form of checking a role is

HttpContext.Current.User.IsInRole("Administrator")

many developers will create page helper methods so you can end up with something more concise for your application like

public static bool IsAdmin(this ViewUserControl pg)
{
    return pg.Page.User.IsInRole("Administrator")
}

then in your view you can just use this.IsAdmin()

To keep your view clutter down look into using partial views

<% if (IsAdmin())
   {
      Html.RenderPartial("AdminPanel");
   }
   else
   {
      Html.RenderPartial("UserPanel");
   }
%>
like image 106
Todd Smith Avatar answered Sep 24 '22 10:09

Todd Smith


If the display changes based on the role -- and the change is small -- then I would do the check in the view. If certain views are restricted based on the role, then I would do the check in the controller. If the views are completely different (this would be hard to imagine), then separate views per role may be appropriate.

You may want to abstract out certain role-specific view components into partial views to simplify your view logic -- basically you only have to check to include the partial or not based on the role.

Also, other than to check for "IsAuthenticated", I would move the role checking logic to the controller and pass (as data) to the view information on which elements to include/exclude based on role. This keeps the actual business logic from bleeding into your view.

like image 26
tvanfosson Avatar answered Sep 25 '22 10:09

tvanfosson


If you are using MVC the whole point of development is to keep the logic out of the view and in the controller. It seems to me like you'd be better off on a WebForms development track than an MVC track.

All that being said, I do an Admin check on a lot of my pages by using a check like this:

<% if ((bool)ViewData["Admin"]) { %>
    <!-- Show admin controls here -->
<% } %>

But if you are attempting to build actual logic into the View then you need to figure out what you can push back to the controller to do the work and have the view be as dumb as possible, acting on flags sent to it.

like image 30
thaBadDawg Avatar answered Sep 23 '22 10:09

thaBadDawg