input name and id changes when set runat=server input name and id changes when set runat=server asp.net asp.net

input name and id changes when set runat=server


This is because you're using MasterPages.

Controls contained within a content page take on a dynamic ID based on the Master Page hierarchy in order to avoid duplication of IDs.

If you need to reference the control IDs and names in client-side script, you can use <%= first_name.ClientID %>.

If you're using .NET4 you can use ClientIDMode="Static" to make the generated IDs consistent, although this comes with its own ID-conflict caveats when, for example, using multiple instances of the same user control on a page. Rick Strahl outlines those here.

However, if you're using ASP.NET validators then everything should be fine. Instead of using an HTML input you should use an ASP.NET TextBox control:

<asp:TextBox id="first_name" runat="server" CssClass="formright" />


ClientIDMode="Static"

This usefully locks the ID of any runat="server" control, however it does not lock the 'name' attribute of a html input element.

Seeing in this instance the only reason to have the runat="server" attribute on the input is to use .Net validation, I would suggest using an external JS library such as jQuery to handle this.

If however, like me, you need to alter the value attribute, the only work around I can see is a rather messy one. If you remove the runat="server" from the input, you can place a server control, such as a literal, within the value="" attribute.

For example:

<input id="first_name" class="formright" type="text" name="first_name" value="<asp:Literal id="litFirstNameValue" runat="server" />"  />

Please don't have a go at me for such bad coding practises, it's intended as a last resort workaround to keep the name attribute from changing to a .Net style name.

Does anyone else know of another way to fix the name? (The form element is not defined as runat="server", but it's embedded within the normal .Net form, which is why the server is attaching it to the main form tree)


ClientIDMode only affects IDs. if you also need to manage name attribute then it's useless. In my case I solved this on the client side with jQuery.

$(function(){    $("#inputname").prop("name",$("#inputname").prop("id"));});