views:

88

answers:

2

When you assign something an ID in asp.net such as:

<asp:Label runat="server" ID="mylabel" Text="some text"></asp:Label>

The code behind ID you use to reference that object is mylabel.

However after the site has compiled and is running the ID in the HTML changes to something a bit more abscure

<asp:Label runat="server" ID="ct100_blahblah_what_mylabel" Text="some text"></asp:Label>

And I cannot (don't know how) to reliably predict what it will be to select it with javascript.

Is there a way to ask the server what the ID for that label is at any given moment?

What are some keywords could use to find out more about this phenomenon?

+3  A: 

I believe you are looking for the ClientID property.

The ClientID value is often used to programmatically access the HTML element rendered for a control in client-side script.

Your other option is to wrap your control in an HTML element like this:

<span id="foo">
    <asp:Label runat="server" ID="mylabel" Text="some text"></asp:Label>
</span>

Since this outer element does not have the runat="server" attribute, its id will not be changed on render. This would mean that your JavaScript function would have to to be changed to pull an inner element from the span foo or if you are using a JavaScript framework like jQuery you could pull the label back like this:

$("span#foo span");
Andrew Hare
Could I have an example please?
aggitan
+3  A: 

You need the ClientID property. This contains the generated id of the control at runtime. You could emit some JavaScript in the code behind that sets the client id of your control to a JavaScript variable so you can reference it.

EDIT: added example

The following will find the label using the ClientID and then update its text.

    <html>
    <body>
        <asp:Label runat="server" ID="mylabel" Text="some text"></asp:Label>

        <script language="javascript">
            var mylabelID = "<%= mylabel.ClientID %>";
            var label = document.getElementById(mylabelID);
            label.innerHTML += " changed";
        </script>
    </body>
    </html>
adrianbanks
Could I have an example please?
aggitan