INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

asp.net and AJAX

Simple AJAX using the .NET 2.0 ICallbackEventHandler by jshurst
Posted: 25 Sep 06 (Edited 12 Feb 07)

AJAX is a hot topic right now and I didn't see any FAQ's on it in this forum so I thought I would show you how I'm implementing AJAX functionality on one of my sites.

AJAX stands for Asynchronous JavaScript and XML.  Don't worry if you don't really know JavaScript (yet) or XML (you don't really need to specifically know this to use AJAX), as I will show you all you need to know to do this example.

So let's begin...

First create a simple web page with a few labels, a textbox and a button on it.

CODE

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Test.aspx.vb" Inherits="Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="head1" runat="server">
    <title>Untitled Page</title>

    <script language="javascript">
   //First we have the function to initiate the call to the server
    function StartAJAXProcedure()
        {
            
            var Command = "1:" + document.getElementById('txtInput').value;
            var context = new Object();
            context.CommandName = "GetDetails";
            window.status="Getting Details.  Please wait...";
            
            //This is where the "magic happens"
            //In the page load event we are going to register this script
            <%=callbackString %>
        }
   
        
        
        //This is the function that will handle the string returned from the server
        //Different functions can have different "context's"
        // You pretty much can only return a string, so this is where you must be creative
        //Also have a look at the JSON (JavaScript Object Notation - which is beyond the scope of this FAQ)
        function CallBackHandler(result, context)
        {
            if (context.CommandName == "GetDetails")
            {
            
                //Splitting the string returned by the server
                SplitResults = result.split("| |");
                
                {document.getElementById('lblOutput1').innerHTML = SplitResults[0];}
                {document.getElementById('lblOutput2').innerHTML = SplitResults[1];}
                {document.getElementById('lblOutput3').innerHTML = SplitResults[2];}
                
                window.status="Complete.";
            }
        }
        
        
        
        //handler for errors
        function onError(message, context)
        {
            //Displaying a pop-up box if any error occurred
            alert("Exception :\n" + message);
            window.status="An error has occurred.";
        }
   
    </script>

</head>
<body>
    <form id="form1" runat="server">
        <asp:TextBox ID="txtInput" runat="server" />
        <br />
        <asp:Label ID="lblOutput1" runat="server" />
        <br />
        <asp:Label ID="lblOutput2" runat="server" />
        <br />
        <asp:Label ID="lblOutput3" runat="server" />
        <br />
       
        <input id="btnSubmit" type="button" onclick="StartAJAXProcedure()" value="Start AJAX" />
       
    </form>
</body>
</html>

And then the code-behind page...

CODE

Imports System
Imports System.Web
Imports System.Data


Partial Class Test
    Inherits System.Web.UI.Page
    Implements ICallbackEventHandler

#Region "AJAX Variables"

    'Since the ICallBackEventHandler uses two functions we need a page-level variable so that we can return the string
    Dim results As String

    'We need this so that we can register the string in the .aspx page from the page_load event
    Public callbackString As String

#End Region

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            'Adding the script for AJAX
            callbackString = Page.ClientScript.GetCallbackEventReference(Me, "Command", _
                             "CallBackHandler", "context", "onError", False)

           
        End If
    End Sub

#Region "AJAX Events"

    Public Function GetCallbackResult() As String Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult
        'The "only" job of this server-side function to return the results to the JavaScript function
        Return results
    End Function

    Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent

        'This is the function that get's called from the JavaScript function (it will do all the work)
        'I've been using the "StartsWith Method in case I have more than one JavaScript function that might do different things
        If eventArgument.StartsWith("1:") Then
            'Here I normally go to a database to get some data, but I'm just going to do a simple string builder to save time

            Dim myString As New StringBuilder

            With myString
                'Let's get what we passed over first and return it
                .Append(eventArgument.Substring(eventArgument.IndexOf(":") + 1))

                'Now I'm going to add a separator so that I can split this string up on the javascript side
                'This can be whatever you choose, but try to make sure it's a pattern that won't normally get returned in your results
                .Append("| |")
                .Append("This is my second AJAX result!")
                .Append("| |")
                .Append("This is my third AJAX result!")
                'And so on...
            End With

            'setting the result page-level variable
            results = myString.ToString
        Else
            'If we had another calling JS function we could put it here
            results = "New Function that we haven't created yet..."
        End If

    End Sub

#End Region
End Class

And finally a few things to keep in mind.

1) Asp.net controls, once they are processed through IIS, are sent to the browser as regular html controls - for example a asp:label = span, an asp:textbox = input type="text".  So you might not need to use asp.net controls in your application (and the Javascript might be different for accessing the values, i.e. .value or .innerHTML)

2)  You can return "any" string.  So you could write an entire table to a div or a span if you wanted.  However some special characters are reserved by JavaScript, just be aware if you are experiencing weird errors.

3)  If you can you might want to use MS Atlas, because you don't have to write any JavaScript.

4)  The page_load will always get fired (even when using AJAX), so be aware of what you are doing there.

EDIT:  I has come to my attention that I am slightly mistaken when I say that you can only return strings.  You can also access XML files, but that is beyond the scope of this FAQ.

Back to Microsoft: ASP.NET FAQ Index
Back to Microsoft: ASP.NET Forum

My Archive

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close