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

后端 未结 8 1389
南方客
南方客 2020-12-04 11:22

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

8条回答
  •  无人及你
    2020-12-04 12:12

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

提交回复
热议问题