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!

Published Tuesday, July 03, 2007 12:48 PM by Palermo4
Filed under: , , ,

Comments

# re: Accessing Server Controls From Client Script

Tuesday, July 03, 2007 12:58 PM by Monty

Im quite sure you can see all this info from the asp.net trace at the bottom, no?

# Accessing Server Controls From Client Script

Tuesday, July 03, 2007 3:05 PM by DotNetKicks.com

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# re: Accessing Server Controls From Client Script

Tuesday, July 03, 2007 6:45 PM by Palermo4

Monty,

The alert was simply to demonstrate how to access the client id programmatically.

# University Update-AJAX-Accessing Server Controls From Client Script

Pingback from  University Update-AJAX-Accessing Server Controls From Client Script

# re: Accessing Server Controls From Client Script

Wednesday, July 04, 2007 12:57 PM by Dave

That's a good idea.

I've been struggling a little bit with control IDs, trying to add some client scripted pizazz to a series of controls nested in a repeater.  This tip looks to make my life much easier, thanks!

# re: Accessing Server Controls From Client Script

Thursday, July 05, 2007 11:24 AM by Palermo4

Dave,

Glad to help!

# bathroom vanities

Tuesday, July 31, 2007 11:34 AM by bathroom vanities

bathroomdesign.greatnow.com/bathroom-vanities bathroom vanities

# bathroom faucets

Thursday, August 02, 2007 4:02 PM by bathroom faucets

bathroomdesign.greatnow.com/bathroom-faucets bathroom faucets

# re: Accessing Server Controls From Client Script

Friday, February 01, 2008 2:40 AM by gkopparam

how do i use that when i want to have a separate  java file that does client side validation on a server control ?

thanks

Leave a Comment

(required) 
(required) 
(optional)
(required)