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

devforall picture devforall · Jan 3, 2009 · Viewed 16k times · Source

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?

Answer

Todd Smith picture Todd Smith · Jan 3, 2009

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");
   }
%>