views:

49

answers:

4

When you have an ASP control like this:

<asp:TreeView ID="TreeItems" runat="server"></asp:TreeView>

The html that it generates mangles the names. If I want to access the ids of the generated items directly, I can try and figure out what it mangles the names to and look for that ID.

Are the names of the items generated guaranteed to be done in a specific way by whatever standard there is from Microsoft? I'm just afraid of this breaking if they release a new version of .NET that does it in a different way. Is there a way to generate the name mangling myself in code?

+5  A: 

It isn't guranteed to be consistent (it's an implementation detail)

Use ClientID instead (which gives you the generated id).

BioBuckyBall
this works, but I hate mixing languages
mgroves
A: 

No, it's not guaranteed to be consistent.

It should be consistent as long as the same version of the framework is used, but updates to the server may change this, so you shouldn't rely on knowing the generated name.

Use the ClientID property to find out the generated id of a control.

Guffa
Also, as long as you're inside the same naming container.
Joel Coehoorn
+1  A: 

If you want to use it in a client-side script, you can do the following:

<script type="text/javascript">
    //initialize client names of server side controls.
    var TreeItemsId = "<%= TreeItems.ClientID  %>";    
</script>

When it renders out to the client it'll look like something like this:

<script type="text/javascript">
    //initialize client names of server side controls.
    var TreeItemsId = "ctl00_TreeItems";    
</script>
Greg
+3  A: 

I believe with ASP.NET on .NET 4, you can specify that the IDs be generated a certain way.

See: http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx

Additionally, if you are using jQuery, you can be sure that the nominal ID will be in the client ID, so you could select it with something like:

$("input[id*='TreeItems']")

See: http://api.jquery.com/attribute-contains-selector/

mgroves
Your selector has the pro/con that it can find all of the controls created with the same ID inside of a template.
Greg