Accessing Server Controls From Client Script

In our AJAX QuickBuild event yesterday, Simon Allardice demonstrated for everyone how to access the value of a server control from client-side script.  Let me share with you his tip/trick.  It is quite simple.  Here is the markup of a content page - notice the script tag:

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" Title="Who Cares?" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div>
        <asp:Label ID="LabelMessage" Text="In Content control" runat="server"></asp:Label>
    </div>

    <script type="text/javascript">
        alert($get('<%=LabelMessage.ClientID %>').id);        
    </script>

</asp:Content>

Note the script element contains server code to request the client id of the control.  When this page executes, the following alert appears:

ajax.clientid.alert

Because ASP.NET will alter the ID of a server control based on a variety of reasons, accessing the client id is the best way to get the actual rendered id!  Thanks Simon!

5 Comments

Comments have been disabled for this content.