Role-based enabling/disabling of controls in asp.net

纵饮孤独 提交于 2019-11-29 12:24:35

This was the really good question clicking my mind last year.. this is what i came up with, its a bit lengthy but i hope this could help..

First you will have to take a look at ControlAdapters in Asp.net.

http://www.asp.net/cssadapters/WhitePaper.aspx

Overview: 1.Create a control adapter for a control type you want to enable and disable based on roles. 2.apply some attribute on asp.net controls, that specify which roles can access that control.

in asp.net page try some thing like this

<asp:TextBox ID="TextBox1" runat="server" CRAN="1"></asp:TextBox>

here CRAN is my custom attribute and 1 is the roleid that can access this control on page.

now its time to create a Control Adapter that will enable/disable this control based on roles.

public class TextBoxAdapter:
     System.Web.UI.WebControls.Adapters.WebControlAdapter
    {

        protected override void OnLoad(EventArgs e)
        {
            if (this.Page is ISecurable)
            {
                WebControl tb = this.Control as WebControl;

                string roles = tb.Attributes[Constants.ControlRoleAttributeName];
                bool result = true;
                if (!string.IsNullOrEmpty(roles))
                {
                    result = false;
                    string[] role = roles.Split(',');
                    foreach (string r in role)
                    {
                        if (Roles.IsUserInRole(r))
                        {
                            result = true;
                        }
                    }

                }

                tb.Enabled = result;
                //tb.BackColor = Color.Red;
            }
            base.OnLoad(e);
        }
    }

this is the control adapter i have created this will enable/disable the control based on roles. you can modify this show/hide control.

you will have to register this control adapter in App_Browser folder of asp.net in a .browser file

<browsers>
  <browser refID="Default">
    <controlAdapters>

     <adapter controlType ="System.Web.UI.WebControls.TextBox" adapterType="MyProject.ControlAdapter.TextBoxAdapter" />
    </controlAdapters>
  </browser>
</browsers>

Conclusion: You will have to only apply an attribute on element in order to show hide them. i have created adapter for Textbox you can try creating some generic adapter like WebControl/Control.

Regards.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!