views:

92

answers:

2

In ASP.NET, when you give a tag an ID it generates a unique HTML id for the element based on the control hierachy, ie.

<asp:Panel ID="test" runat="server">
    ...
</asp:Panel>
<!-- Becomes... -->
<div id="plc_lt_zoneContent_PagePlaceholder_PagePlaceholder_lt_test_test">
    ...
</div>

Is there some way of determining the generated id in the codebehind file? I need to generate some Javascript that uses the id.

+6  A: 

Do this in javascript:

<script type="text/javascript">

  var theID = '<%= test.ClientID %>';
  // theID contains your ID

</script>

Update: I noticed a comment below that ClientId didn't work. It's ClientID (case sensitive). Here's the documentation reference to ClientID:

http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid(VS.71).aspx

Keltex
I get the following ASP error when trying this:error CS1061: 'System.Web.UI.WebControls.Panel' does not contain a definition for 'ClientId' and no extension method 'ClientId' accepting a first argument of type 'System.Web.UI.WebControls.Panel' could be found (are you missing a using directive or an assembly reference?)
Matthew Scharley
while you may have an error with this particular solution. The spirit of his answer does seem like a decent solution. You can output the client Id to javascript after the prerender event.
Mark Rogers
Well, yes, I got that before even asking the question. The question was how to retrieve the client ID, which apparently doesn't seem to exist...
Matthew Scharley
@Matthew... I think it's case sensitive: ClientID not ClientId
Keltex
@Keltex: Of course it is, stupid me for missing that. Cheers, it's all working now! :)
Matthew Scharley
+1  A: 

You can use the ClientID property, but it is only available from the PreRender event (or later).

ASP.NET 4 is going to make some changes to this so that you can get "predicatable" identifiers, but even then it's not a panacea.

Dean Harding