Useful Tips for Master Page Control access in Java Csript
When we use master page in ASP.Net it will append the Content Placeholder Id with the ID of the contained controls.i.e when there is a textbox with ID “txtAccountNumber” it will be rendered as “ctl00_ContentPlaceHolder1_txtAccountNumber” where “ContentPlaceHolder1” is the ID of the Content Placeholder of the Master Page. This makes us to use the ID “ctl00_ContentPlaceHolder1_txtAccountNumber” whenever we want to access it in JScript. We can access the textbox in Jscript like,
document.getElementById(' ctl00_ContentPlaceHolder1_txtAccountNumber ') ;
But the above scenario will leads to script error if we unknowingly change the ID of the ContentPlaceholder in master Page. So whenever we change the ContentPlaceholder ID we need to revisit all the Jscript code and change the corresponding ID’s. To prevent this rework we can register a hidden control from code behind which in turn will hold the client ID of the control.
Page.RegisterHiddenField("hdnAccountNoTextID", txtAccountNumber.ClientID);
Now we can make use of this hidden variable to get the client ID of the textbox in Jscript.
//gets the Client ID of the txtAccountNumber textbox
var AccountNoTextID = document.getElementById('hdnAccountNoTextID').value;
//Access the txtAccountNumber textbox
var AccountNoText = document.getElementById('hdnAccountNoTextID');
By doing this we can prevent the rework even if someone changes the ContentPlaceholder ID in future our script will be executing without any error.
The same scenario applies when we use a control inside user control.
No comments:
Post a Comment