Making your .NET AJAX responses a little easier

If you find value in creating server-side javascript statements that an ajax callback can simply execute with the EVAL statement, then in the ASP.NET environment you have probably found that to be difficult since .NET objects are named differently on the client than on the server. I started to use a little trick that helps me get around that issue with a custom class and a little session caching.


So let’s say you have a Label server control in your ASP.NET form that is called “lblLastName” in the server code, you will have end up with a client side object with an ID like “ctl00_ContentPlaceHolder1_lblLastName”. This makes it difficult to write AJAX response scripts when you use a single AJAX endpoint for all page functions like I do. The AJAX endpoint page does not have access to the originating page’s code where I can use the ClientID method of a server control to find the client side name of an object.

So my little trick is to create a custom class to hold the client side DIV ID’s of all my UI objects. Something like this:


Public Class DivIDs
    Dim _divIdLastNameLabel As String
    Dim _divIdFirstNameLabel As String
    Public Property LastNameLabelDivId()
        Get
            Return _divIdLastNameLabel
        End Get
        Set(ByVal value)
            _divIdLastNameLabel= value
        End Set
    End Property
    Public Property FirstNameLabelDivId()
        Get
            Return _divIdFirstNameLabel
        End Get
        Set(ByVal value)
            _divIdFirstNameLabel= value
        End Set
    End Property
End Class

When the UI page loads, it creates a new instance of this class, uses the ClientID property of the server control to set a class property, and then stores the object in the session cache (or application cache if you choose).

Dim divIds As DivIDs
divIds.LastNameLabelDivId= lblLastName.ClientID
divIds.LastNameLabelDivId = lblFirstName.ClientID
Session("divIds") = divIds

Then when my AJAX endpoint page needs to know the client side ID of any object, I simply pull the object from the cache, and use the property GET method to build my Javascript response.


Dim divIds As DivIds = Session("divIds")
$('" + divIds.FirstNameLabelDivId + "').innerHTML='" + someTextValue + "';
$('" + divIds.LastNameLabelDivId + "').innerHTML='" + someOtherTextValue + "';"

When this response gets back to my client side page, a simple EVAL statement (with the Prototype libraries) will update the appropriate Labels with my server determined values.

Who needs Atlas anyway?!

Leave a Reply