views:

118

answers:

4

Hello, I'm little confused here now. Let me explain:

I've seen people talking about adding a button or some other control to the page in asp.net (3.5) and when the control renders it changes the Id of that control, eg. Button1 becomes Button1_somethingsomething which prevents them from using jQuery and what they end up using is something such as <%controlId.ClientId %>

So I did a little test

1. I added a button on the page:
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server"  Text="Button" />
<div>

2. Then I added a JavaScript and jQuery:
<script type="text/javascript">
                    $(document).ready(function() {
                    $("#Button1").click(function() {
                        alert("Hello world!");
                    });

                    });
                </script>

3. The generated html is this:
<div>
  <input type="submit" name="Button1" value="Button" id="Button1" />
<div>

Now, I don't see ASP.NET (asp.net 3.5) changing the ids. Why do I see different behavior?

Btw. This does work when I hit the button!

Thanks.

+9  A: 

ASP.NET only changes the IDs when the control is inside of a Naming Container. This could include certain user controls, ContentPlaceHolders from a master page, and repeating controls (Repeater, GridView, etc.)

bdukes
A: 

ASP.NET does not change the ID names by default, but does change them when they are used within a ContentPlaceHolder of a master page. So the names end up being something like ctl00_ContentPlaceHolderContent_Button1. In your case, there is no master page and no change is made.

AdamB
A: 

It's due to the INamingContainer Interface that certain controls (such as the asp:content control, used with master pages) implement.

From MSDN:

Any control that implements this interface creates a new namespace in which all child control ID attributes are guaranteed to be unique within an entire application. The marker provided by this interface allows unique naming of the dynamically generated server control instances within the Web server controls that support data binding. These controls include the Repeater, DataGrid, DataList, CheckBoxList, ChangePassword, LoginView, Menu, SiteMapNodeItem, and RadioButtonList controls.

Your sample code does not use any of these controls. You do not use a Master Page with a ContentPlaceHolder. Your IDs are not altered because of this.

ginozola
+1  A: 

You may not always need to use YourControl.ClientID, but it is good practice so that if and when your control DOES end up inside a container, you wont have to go back and fix it.

Neil N