5,662,937 members and growing! (145 online)
Email Password   helpLost your password?
Web Development » Client side scripting » Beginners     Intermediate License: The Code Project Open License (CPOL)

Masterpage and Javascript document.getElementById

By Rajganesh Mountbatton

This article talks about the issues faced in accessing the controls inside a Masterpage from Javascript, and points a quick solution
Javascript, CSS, HTML (HTML), XHTML, ASP, ASP.NET, WebForms, Ajax, Dev

Posted: 13 Dec 2007
Updated: 14 Dec 2007
Views: 23,770
Bookmarked: 17 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
10 votes for this Article.
Popularity: 3.50 Rating: 3.50 out of 5
2 votes, 20.0%
1
0 votes, 0.0%
2
1 vote, 10.0%
3
3 votes, 30.0%
4
4 votes, 40.0%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

Masterpage is one of the good features of the ASP.NET 2.0. But if you are a beginner in .NET 2.0 and Masterpage, you would stuck up in accessing the control which is placed in page inside a Masterpage, from Javascript. Whenever a control is placed inside a page having Masterpage, its client id would be changed. As the clientid is changed, the general document.getElementById(serverID) of the control in the javascript won't work. In this article I would be discussing about the one of the simplest solution to get the clientid of the control in the javascript.

Background

Whenever a control is inside a page having Masterpage the client id of the control would get append with its contentplaceholder id. So for an element of id “txtTest” the client id would be something like “ctl00_ContentPlaceHolder1_ txtTest”.

So when you use the document.getElementById(‘txtTest’), you will not get the access of the txtTest textbox in JavaScript. Indeed you need to access it by calling document.getElementById(‘ctl00_ContentPlaceHolder1_ txtTest’).

To avoid hard coding of the very long clientids, we can access the control by using the document.getElementById('<%=txtTest.ClientID%>').This will give you the access to txtTest text box. Now this will work fine until and unless the script is in line with the aspx page ie., if the script is included as a part of the aspx page. But the same won’t work if you have this script in a separate .js file, and add it to the aspx page by specifying its location.

So in this scenario to get the access to the control, we need to hard code the control’s id. But hard coding is not an ideal way of coding. To avoid this situation what we can do is to, maintain the mapping between the client id and the server id. So in the Javascript, we can get the clientid of the control by giving its serverid. This can be achieved as shown below.

Using the code

The above said can be achieved as described below. First we need to declare two arrays and the first array will have the serverids of the required controls, and the second array will have the clientids of those server controls in the same order. Register these two arrays to the client side. Now create a JavaScript function, which will accept the serverid and will compare the serverid with the available serverids in the array and will give its position in the array. Then the same function would return you the matching clientid in the same location of the clientids array. I feel this is one of the simplest ways of maintaining the maping between the client and serverids.

The code below shows the declaration of the array and the declaration of the JavaScript function in the codebehind.

    // This is the method used to register the array of the clientid's as well as the serverid's


    // Also this method registers the function GetClientId, which is used to get the client id provided server id is supplied


    public void RenderJSArrayWithCliendIds(params Control[] wc)
    {
        if (wc.Length > 0)
        {
            StringBuilder arrClientIDValue = new StringBuilder();
            StringBuilder arrServerIDValue = new StringBuilder();

            // Get a ClientScriptManager reference from the Page class.


            ClientScriptManager cs = Page.ClientScript;

            // Now loop through the controls and build the client and server id's


            for (int i = 0; i < wc.Length; i++)
            {
                arrClientIDValue.Append("\"" + wc[i].ClientID + "\",");
                arrServerIDValue.Append("\"" + wc[i].ID + "\",");
            }
            // Register the array of client and server id to the client


            cs.RegisterArrayDeclaration("MyClientID",
arrClientIDValue.ToString().Remove(arrClientIDValue.ToString().Length - 1, 1)); cs.RegisterArrayDeclaration("MyServerID",
arrServerIDValue.ToString().Remove(arrServerIDValue.ToString().Length - 1, 1)); // Now register the method GetClientId, used to get the client id of tthe control cs.RegisterStartupScript(this.Page.GetType(), "key", "\nfunction GetClientId(serverId)\n
{\nfor(i=0; i<MyServerID.length; i++)\n{\nif ( MyServerID[i] == serverId )\n{\n
return MyClientID[i];\nbreak;\n}\n}\n}"
, true); } }

We can make these codes as part of a common class for all the UI pages like pagebase, so that in each page if need to access any one control in the JavaScript we can simply call the below function with the parameter as the controls to be accessed.

        // Here we need to register the client ids to the client, so that the same can be used in the javascript


        // If there are nultiple controls make it by comma seperated..


        RenderJSArrayWithCliendIds(txtTest);

This is one of the simplest ways to have a mapping between the client and the server id. By this way no need to worry about accessing a control inside a MasterPage from an external javascript files.

After this codes we can access the elements which are given in the RenderJSArrayWithCliendIds function in the javascript as shown below

var TextBox = document.getElementById(GetClientId("txtTest"));

This will slove the issues arrised due to the change in the client id of the control which is placed inside a MasterPage.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Rajganesh Mountbatton


A Developer from India, having more than 3 years of experience in .NET; mostly writing code in C#, JavaScript and AJAX
Occupation: Software Developer
Location: India India

Other popular Client side scripting articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Search Search Messages 
 Layout  Per page   
 Msgs 1 to 11 of 11 (Total in Forum: 11) (Refresh)FirstPrevNext
AnswerEasier solutionmemberCorne.duplooy3:53 21 Oct '08  
GeneralRe: Easier solutionmemberRajganesh Mountbatton4:10 21 Oct '08  
GeneralAwesome!membercwellis9:21 24 Sep '08  
GeneralThanks!membertrujello5:38 7 Sep '08  
GeneralPlease additional explenationmemberDaniel_Moreshet2:22 25 Jun '08  
AnswerRe: Please additional explenation [modified]memberRajganesh Mountbatton19:52 29 Jul '08  
GeneralHow can I get PopWindow page value back to Parent which in using Master Page.memberMember 19344946:14 21 Apr '08  
Generalthank youmemberkevinduk7:39 11 Mar '08  
GeneralNicememberunknownunknown1:28 18 Feb '08  
GeneralThanksmemberGfw6:36 27 Dec '07  
GeneralWrong namememberdennisbetten11:31 17 Dec '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 14 Dec 2007
Editor:
Copyright 2007 by Rajganesh Mountbatton
Everything else Copyright © CodeProject, 1999-2008
Java | Advertise on the Code Project