Monday 26 November 2012

Get the control's ClientID in an external javascript file

When you have a asp.net control inside a content place holder and when the runat="server" attribute is set, asp.net changes the client id to something autogenerated that is a combination of the content place holder and the control id. As a result you will have to get the client id dynamically when you want to retriece the value of a control through javascript.


If you add the javascript directly to the asp.net markup, you can obtain the client id like this:

<script type="text/javascript">
    var elm = document.getElementById("<%=ControlID.ClientID %>");
</script>

Notice the quotes around <%=ControlID.ClientID %>. The expression is evaluated and replaced with the client id eventhough you would believe it would be considered a string.

How to get the client id of a control in an external javascript file

In an external javascript file you can't use the <%=ControlID.ClientID %> to get the client id of a control. You must obtain it with a minimal snipet of javascript in the markup file, and then pass it as a parameter to a function in the external javascript file.

Aspx-file markup file


<script type="text/javascript">
    $(function () {
        sayHi("<%=MyNameTextBox.ClientID %>");
    });
</script>



External javascript file


function sayHi(nameTextBoxId) {
    var nameTextBoxElm = document.getElementById(nameTextBoxId);
    alert( nameTextBoxElm.value );
}



In ASP.NET 4.0 and later you can force asp.net not the change the id of a control - it will have the same id serverside as clientside - by use of the ClientIDMode.
See Cleaner HTML Markup with ASP.NET 4 Web Forms - Client IDs (VS 2010 and .NET 4.0 Series)

No comments:

Post a Comment