ASP.NET Get by ID Override ClientID

Some times we need to use html object’s id s  in javascript or in html source in Masterpage based ,including custom content   and user controls integrated complexed web sites.you know that the object IDs (ClientID) is generated by asp.net   .  When you are using Extjs or JSon kind of stuff its hard to manage and that asp.net generated ids because its long and complex.

An example of Extjs code that need to use id of Portal html object.
Asp.net generates an id like this
“ct100” is control id parent
“cphMiddle1” comming from ContentPlaceHolder id
“ModulePlace1” comming from userControl
“Portal1” object that i want to use its id.

if we sum of those the final id like this :
ctl00_cphMiddle1_ModulePlace1_Portal1
 

if you want to reach object you can find that id just in source code of builded aspx.
var
portal = Ext.getCmp(“ctl00_cphMiddle1_ModulePlace1_Portal1”);
 

 

You can use it for more easy by using like this:
var
portal = Ext.getCmp(“<%=Portal1.ClientID %>”);

There is another way to do it by overriding ClientID and UniqueID of your component.Instead of using base.ID use this.ID

        public override string ClientID
        {
            get
            {
                return this.ID;
            }
        }
        public override string UniqueID
        {
            get
            {
                return this.ID;
            }
        }

But one exception that should be cared about of id confilict.You should extra check for control ids that not conflict in other containers when overriding ClientIDs.

 

One tip : do not use orginal id text of ide created.Example like textboxes in your project can not be standart name of “Textbox1″,”Textbox2”,”Textbox3″… you should change “txtMyControlName”,”txtMyControlAge”,”txtMyControlSurname” or etc.

 

Advertisement