Ajax in Asp.net

In today’s blog entry, I’m going to take a step back from MVC Frame Work and write little bit about Asp.net. We will be focusing on how to make an Ajax call within Asp.net Web Forms. Many programmers had asked me about implementing Ajax in Asp.net Web Forms. This will give me an opportunity to respond to that and besides I get a chance to take a short break from our MVC series.

What we need to get started?

  • Visual Studio 2005 or higher
  • .NET Frame Work 2.0 or higher
  • ICallbackEventHandler :- Interface which is part of the System.Web.UI
  • RaiseCallbackEvent :- Method part of the ICallbackEventHandler that when invoked will communicate with the server.
  • GetCallbackResult :- This method is also part of the ICallbackEventHandler interface that will return results to the client.

Also, we need little bit of JavaScript which we will register onto the page from server side.

  • First function :- Makes that actual request to the server.
  • Second function :- Handles an error that come up during the call.
  • Final function :- This is that main function that will be responsible for making the Ajax call. Also, it will be automatically generated by Asp.net. You will see in a sec.

Here is the code of the Page_Load event :-

protected void Page_Load(object sender, EventArgs e)
{
     #region Generic ajax call script registration 
     string js = Page.ClientScript.GetCallbackEventReference(this, "arg", "OnReturnedData",
            "ctx", "OnError", true);

     //create a simplified wrapper method
     StringBuilder newFunc = new StringBuilder();
     newFunc.Append("function StartAsyncCall(arg, ctx) ");
     newFunc.Append("{ "); 
     newFunc.Append(js);
     newFunc.Append(" } ");

     //register it
    Page.ClientScript.RegisterClientScriptBlock(typeof(Test), "AsyncMethod",
                       newFunc.ToString(), true);
     #endregion
}

Couple of things are happening here, which are quite simple as you will soon see:-

1. Page.ClientScript.GetCallbackEventReference(control, argument, clientCallback, context, async)

  • control :- Server control that handles the client callback. This control must also implement ICallbackEventHandler interface & provide a RaiseCallbackEvent method. In our case, it’s the page itself.
  • argument :- Arguments passed from the element script to the server.
  • clientCallback :- The name of the client event handler that receives the result.
  • context :- Client script is evaluated on the client prior to initiating callback. The result of the script is passed back to the client event handler.
  • clientError :- Client event handler that handles the error.
  • useAsync :- Set true to perform callback asynchronously, false for synchronously.

2. Function StartAsyncCall will be regenerated automatically which we will call within our custom JavaScript function.

3. The last line, simply registers our JavaScript on to the page.
Page.ClientScript.RegisterClientScriptBlock(typeof script, key, script string, add script tag);

Now, we got that over with, it is time to inherit from ICallBackEventHandler.

complete c# code of our Test.aspx.cs page:-

 public partial class Test : Page, ICallbackEventHandler
{
    public string retVal = string.Empty; //global variable that will store our return value
    protected void Page_Load(object sender, EventArgs e)
    {
        #region Generic ajax call script registration
        
        string js = Page.ClientScript.GetCallbackEventReference(this, "arg", "OnReturnedData",
                "ctx", "OnError", true);

        //create a simplified wrapper method
        StringBuilder newFunc = new StringBuilder();
        newFunc.Append("function StartAsyncCall(arg, ctx) ");
        newFunc.Append("{ ");
        newFunc.Append(js);
        newFunc.Append(" } ");

        //register it
        Page.ClientScript.RegisterClientScriptBlock(typeof(Test), "AsyncMethod",
                            newFunc.ToString(), true);

        #endregion
    }

    #region implement ICallbackEventHandler Members
    public string GetCallbackResult()
    {
        //return value back to client side
        return retVal;
    }

    public void  RaiseCallbackEvent(string eventArgument)
    {
        //do the server side process here....
        retVal = eventArgument;
    }
    #endregion
}
Simple enough for you…

Complete HTML code for our Test.aspx:-

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Untitled Page</title>
    <script language="javascript">
       
       //Global variable for our container div
        var objContainer = null;
       
        //Our custom javascript function that will be invoked by some kind of event.
       //In our case, AjaxTest() is being invoked by the onclick event.
        function AjaxTest()
        {
            //user input
            var objInput = document.getElementById("txtInput");
            
            //get container element 
            objContainer = document.getElementById("container");
            
            //dispaly a loading message in the container before the call...
            objContainer.innerHTML = "loading....";
            
            //call the autogenerated ajax call function.
            StartAsyncCall(objInput.value);
        }

        //When everything goes well, OnReturnedData function will -
        //handle our returned data.
        function OnReturnedData(arg, ctx)
        {          
            //clear the content of the container
            objContainer.innerHTML = "";

            //than display the return data from the server.
            objContainer.innerHTML = "Respond from server:- Hi! " + arg;            
        }

        //When things go wrong OnError() function will come in handy...
        function OnError(err, ctx)
        {
            //display error message in our container
            objContainer.innerHTML = err; 
        }

    </script>
</head>
<body>
<form id="form1" runat="server">
    Type your name to talk to the server:
    <input id="txtInput" name="txtInput" type="text" size="40px" />
    <a href="#" onclick="AjaxTest();">Submit Name</a>
 <div id="container" style="color: Red;"></div>
 </form>
</body>
</html>
Here is what the final output would look like:-
aspnetfinaloutput
Look!!! maa, No page refresh….

I hope this blog entry will help you to add creativity to your web application.