I've 开发者_开发百科a control
<asp:Button ID="btnAjax" runat="server" Text="Ajaxified" OnClick="btnAjax_Click" />
Now from the code behind I want to change the ID of the button
btnAjax.ID = "newButtonID";
But it is now working. Is it possible at the first place?
EDIT
I've created the control in the HTML mark up and not through code.
Yes it is possible and your code you posted will work.
I have a button and a text field
<asp:Button ID="button" runat="server" />
<input type="text" id="result" name="result" runat="server" />
On page load I change the ID of the button and then output the result to the text field.
protected void Page_Load(object sender, EventArgs e)
{
button.ID = "OtherButton";
result.Value = button.ID;
}
The result in the text field is "OtherButton"
Yes you can that Property is both read and write [able].
I tried and yes the ID can be changed and its also reflected in rendered HTML.
Update
There is a ClientIDMode attribute which you can set to 'Static' that you can use to force asp.net into not changing the ID in rendered HTML.
<asp:Button ID="Button1" runat="server" Text="Button" ClientIDMode="Static" />
The only reason I can imagine one would need to achieve something like this is to safely allow client script to interact with the button. If this is the case then I prefer to pass the control's clientID to the script:
var btnAjax = document.getElementById('<%=btnAjax.ClientID%>')
Or using jQuery:
$('#<%=btnAjax.ClientID%>')
精彩评论