AJAX Without ASP.NET AJAX

On day nine of my "post a blog every day in July" mission, I want to share how to get AJAX behavior in ASP.NET without using AJAX Extensions 1.0.  Keep in mind, I prefer to use AJAX Extensions!  This blog is for those out there that need a sprinkle of AJAX on their site, but are not allowed (for whatever reason) to install AJAX Extensions.

First, I will implement an interface on the web form:

<%@ Page Language="C#" %>
<%@ Implements Interface="System.Web.UI.ICallbackEventHandler" %>

Here are the two required methods the above interface requires:

public void RaiseCallbackEvent(string eventArgument)
{

    Context.Items["callback.value"] = eventArgument;
}

public string GetCallbackResult()
{
    return "<h1>" +
        Context.Items["callback.value"].ToString() +
        ": " +
        DateTime.Now.ToLongTimeString() +
        "</h1>";
}

In the methods above, I use the Context.Items collection to pass data from one method to another.  RaiseCallBackEvent is called first.  The eventArgument is passed in by client-script (seen in code below).  What the client receives back is processed by GetCallbackResult.

Now it is time to "wire-up" or register the client script to use these methods.  I do this all in the Init event of the page:

protected void Page_Init(object sender, EventArgs e)
{
    // register client script for receiving results
    ClientScript.RegisterClientScriptBlock(this.GetType(), "ReceiveCallbackResultFromServer",
        "function ReceiveCallbackResultFromServer(results){ document.getElementById('changeMe').innerHTML=results; }", true);

    // how to call "ReceiveCallbackResultFromServer"
    string howToCallReceivingFunction =
        ClientScript.GetCallbackEventReference(this, "valueFromInput", "ReceiveCallbackResultFromServer", "");

    // how to call "SendDataToServer"
    string howToCallRaiseCallbackEvent =
        "function SendDataToServer(valueFromInput, context) {" + howToCallReceivingFunction + "}";

    // register client script for sending data to server (this page)
    ClientScript.RegisterClientScriptBlock(this.GetType(), "SendDataToServer", howToCallRaiseCallbackEvent, true);

    // set client click to invoke "SendDataToServer" function
    ButtonTest.OnClientClick = "SendDataToServer(document.getElementById('textBox').value);return false;";
}

Finally, here is the markup of the web form:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <div id="outerDiv">
            <input id="textBox" runat="server" />
            <asp:Button ID="ButtonTest" runat="server" Text="Test Client Callback" />
            <div id="changeMe">
            </div>
        </div>
    </form>
</body>
</html>

When the page runs, the value in the input with the id of "textBox" is sent to the server.  The server receives the value in RaiseCallbackEvent method via the eventArgument.  ASP.NET then processes a result to send back to the client in the GetCallbackResult method.  In this example, I return a heading tag with the value of the textbox plus date & time info.  The client script needed to call the server and receive the results are found in the Page_Init handler.

Of course, an UpdatePanel makes this much easier :-)

4 Comments

  • There's no need to do this in the Page_Init - in fact that's probably the last place you should be doing it unless you need to implement this event before everything else on the page excecutes - Page_Load is perfectly acceptable to do this.

    In addition, your call should really be surrounded by an if(!Page.IsCallBack) {} statement so the server doesn't try and run it again when the callback is executed.

  • GH,

    I looked over my post and did not see that I said that this must be done in Page_Init. Having said that, you did not indicate why Page_Init is problematic. This implementation works as is.

    With regard to !Page.IsCallBack... you are absolutely correct :)

  • Interesting is that you can also use this in UserControls, which could be an alternative for ASP.NET AJAX Page Methods.

    You can put the ajax handler in the control (independent of where it is used) and you can access the state of the control while handling the callback...

  • Great Article! I will be giving this a try. Too many people are dependent on prepackaged controls. Its nice to see someone showing how its done in raw code. Thanks!

Comments have been disabled for this content.