Archive

Archive for April, 2009

A Generic way to Get IDs of server controls in java-script

April 25, 2009 Leave a comment


While working with ASP.Net and java-script, we need to manipulate the HTML objects on the form. If these objects are coded as server side controls, the ids on the client side are different to what we have on the server side.

E.g. a server side text box added in a page with ID=textTitle will have its client id=ctl00_ContentPlaceHolder1_textTitle. (ctl00 is sequence identifier, ContentPlaceHolder1 is id of the parent container and txtTitle is the actual object id) The value of the client id depends on the location of the control, if we add the same control in a different position or we move it inside a user control, its client id will be different.

So one option is to hard-code its client id to access the object in java-script. But this option does not seem appropriate, as the client id can be different with time, with either addition of the new controls or with moving the object to a user control or a similar reason.

Following approach solves this problem to some extent; this approach automates the process of mapping the server and client ids of all objects on a page.

  1. Include the jsClientHtmlObjects.js into the page.
  2. Add the code mentioned in the BasePage.cs to your page class (or its base class)
  3. Include the following script to the end of the page.aspx file just before the </body> tag:

    <
    script type=”text/javascript” language=”javascript”>
             <%=ClientObjectsList%>
    </script>
  4. In Javascript, where you want to access the client instance of the server side object, call the mthods:
    • objClientHtmlObjects.GetObject(serverID) //To get the HTML object with the passed server id
    • objClientHtmlObjects.GetValue(serverID) //To get the HTML object’s value with the passed server id
Categories: C# Tags: