How-to use ClientIDs in JavaScript without the ugliness

ASP.Net has an interesting way of handing the potential ID conflicts caused by embedding third-party controls within your web-page; it prefixes any sub-controls with their parent’s ID.

<asp:TextBox ID="txtUsername" Runat="server" /> within a standard page simply has an ID of txtUsername within the HTML output. On the other hand, the following example would result in something along the lines of _parent_txtUsername as the ID:

<div id="parent" runat="server">
  <asp:TextBox ID="txtUsername" Runat="server" />
</div>

This isn’t really much of a problem when all you are working with is server-side code, but when you start tinkering with JavaScript, things become quite annoying and get an overall feeling of hackyness.

One solution, which I have used time-and-again, is to use a script block at the end of your page where you create a series of variables that contain the actual IDs. You then use these variables to reach the actual elements via JavaScript.

<script type="text/javascript">
  var txtUsernameID = '<%= txtUsername.ClientID %>';
  var txtPasswordID = '<%= txtPassword.ClientID %>';
</script>

This solution works fine, but it isn’t exactly pretty and it doesn’t weigh well on my conscience.

Javascript Mapping

I’ve created a simple class that traverses the control structure and outputs an object that contains the mappings, as above, but without any client-side intervention; not a <%= ...ClientID %> in sight.

An example of the output would be:
var ClientIDs = {
  txtUsername = 'ctrl0_txtUsername',
  txtPassword = 'ctrl0_txtPassword'
};

Which enables you to reference elements, that you know are server-controls, by calling ClientIDs.txtUsername.

Before:

<script type="text/javascript">
  var txtUsernameID = '<%= txtUsername.ClientID %>';
  var txtPasswordID = '<%= txtPassword.ClientID %>';


  function validate() {
    var username = $(txtUsernameID).value;
    var password = $(txtPasswordID).value;


    if (username == 'james') {
      alert("you shouldn't be here!");
    }
  }
</script>

After:

<script type="text/javascript">
  function validate() {
    var username = $(ClientIDs.txtUsername).value;
    var password = $(ClientIDs.txtPassword).value;


    if (username == 'james') {
      alert("you shouldn't be here!");
    }
  }
</script>

ServerControlIDs class

Methods

void Emit(page) - Builds the controls of the page into a mapped structure, registering a client-side script block for the output.

void Emit(control, literal) - Builds the controls of the control into a mapped structure, rendering the output into the literal control supplied. The literal is best suited to being placed into the <head> tag, which helps improve the semantic nature of your page.

Properties

bool Whitespace - Sets whether the output should contain whitespace, provided only for “prettifying” your code; defaults to off.

string VariableName - Sets the JavaScript variable name used; defaults to ClientID.

Usage

To use this class, simply create an instance in the PreRender event for your page — this ensures that all the controls have been set to their correct state — then call the Emit method you desire.

History

[1.1] Removed IDs from Repeater/DataGrid contained controls.
[1.0] Initial release

Download

That’s all there is to it, use the link below to get the latest version of ServerControlIDs.

Please note that this code isn’t pretty and it could probably do with some revising, but it works and that’s what’s important to me. I’m open to suggestions and feature requests.

Current Version (1.1)

Comments 7

  1. Thurein wrote:

    Your effort is much impressive.
    It is truely workable for ASP.NET 1.X.
    But as far as I concern, you might need to add some coding to exclude new repeater controls in ASP.NET 2.0.
    For instance, GridView,FormView,DetailsView etc.

    Posted 29 Aug 2007 at 8:03 am
  2. James Gregory wrote:

    You are correct, this was written before I’d started using .Net 2 my self. I should really update it, but in the meantime the source code is available.

    Posted 29 Aug 2007 at 9:20 am
  3. Tan wrote:

    Hi,
    It seems your link to download the zip file is not working,
    Could you please fix the link to download the file

    Posted 18 Jun 2008 at 1:21 pm
  4. Rick wrote:

    Greetings. I planned to download your project and save myself a bunch of time - but it’s no longer available. Is there an alternative download location? Thanks!

    Posted 19 Jun 2008 at 6:43 pm
  5. Naz wrote:

    Thanks James, very helpful! Exactly what I was looking for. I’m using your scripted variable concept to pass a server control’s client id through a button’s OnClientClick event to a javascript in .Net 2 and it works like a charm. All other methods that I had tired thus far had failed in my given context for one reason or another.

    Posted 19 Jun 2008 at 8:55 pm
  6. James Gregory wrote:

    Ian, Rick: I’ve fixed the download link.

    Naz: Glad you found it of some use!

    Posted 20 Jun 2008 at 7:40 am
  7. KlimUser wrote:

    Hello James!!
    I left a comment a few days ago but i don’t see them =S
    Last time i visited your Blog, they say that they were waiting for moderation.
    Well I get back ina afew days =)
    Greetings!!!

    Posted 12 Aug 2008 at 9:18 pm

Trackbacks & Pingbacks 1

  1. From Dev 4 Web » Best way to put control ClientId inside JavaScript on 05 Nov 2008 at 12:49 pm

    [...] http://blog.jagregory.com/2006/04/12/how-to-use-clientids-in-javascript-without-the-ugliness/ [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *