ASP.Net Client Callbacks and AJAX Patterns
Download CodeDownload Screen shots Introduction
Two problems with traditional asp.net pages;
1. When some event happens, they require full page postback, no matter how small is the request, and renders the entire page which consumes too much of end users time.
2. It uses click and wait interaction pattern i.e. it does synchrounous communication which disrupt the user work flow and degrade the user experience.
To solve these problems we have Asp.net AJAX (Asynchronous Javascript and XML) which uses asynchronous client callback techniques to communicate with the server. By using ajax techniques user can interact with the application while the data is being processed on the server.
But to create AJAX style applications you do not always need to implement asp.net ajax. Asp.net have a builtin client callback mechanism which encapsulates the logic that performs the asynchronous client callbacks and provides you with a convenient API that you can use to develop Ajax-enabled controls. The client callback mechanism allows clients to call server-side methods. These methods normally retrieve the required data from the underlying data store, format the retrieved data (normally XML format), and return the formatted data to the client.
The client callback mechanism allows client side code to asynchronously call server side methods and use the values returnes from these methods and the HTML/XHTML, CSS, DOM, and JavaScript client side technologies to dynamically update the approprate parts of the page without having to perform a full page postback and consequently render the entire page again.
The major reference of this tutorial are the chapters 26 to 29 from the book by Dr. Shahram Khosravi, "Professional Asp.Net 2.0 Server Control and Component Development". For detailed and indepth understanding you should consider reading the book.
Client Callback Mechanism Steps
In asp.net 2 making a client callback is a 4 step process:
1. First of all you need to retrieve some data from the client side, which is accessed by using DOM and JavaScript.
2. The data accessed in step 1 will be sent to the server side function which will process the data, for that you need a client side fucntion which will call that server side method asynchronously.
3. The server method called asynchronously in step 2 will now process the data and then return the some result back to the client.
4. The result produced in step 3 by the server and sent to the client will be used to update the client by using DOM and JavaScript.
More detailed description of the steps can be found on Page 829-830 of Professional Asp.Net 2.0 Server Control and Component Development by Dr. Shahram Khosravi.
The ASP.Net 2 Client callback Mechanism
The client callback mechanism consists of different components and asp.net 2 framework comes with built-in implementation for these components. Step 2 and 3 of client callback mechanism defined above have a built in support in asp.net 2 which is implemented by implementing Page.ClientScript.GetCallbackEventReference method and ICallbackEventHandler interface (explained later).
To implement the steps defined above we will use the following case.
Case:
Assume we have a registration module, where users need to select unique username, but before submitting any data we want to give user the functionality to check whether the user name is available or not. We will implement the requirement of username validity by implementing asp.net client callback mechanism, as you do not need a full page postback for these kind of requirements. Assume that our registration module is working with Asp.net built in Membership API, so that we can use the method IsUserExists(string username), without going into any database details.
So let's set the stage first. We need a html text box and a html button and a span. I am using html textbox control and not the asp.net textbox becuase it will be easier to access it through DOM. The button can be a html control in your real application, it will not have any issue. Your page should look like the following image.
Brief description of the process
When the button is clicked a javascript function will access the value of the textbox using DOM and then make an asynchronous call to the server side function and passes the text box value as an argument. That server side function uses the value to check whether the user exists or not and returns a string indicating 'user name available' or 'user name not available'. Then another javascript function takes the string returned by server side method and put that value in a span.
Javascript functions
As the process defined above, the first thing we need to access the value from the user name textbox. So we create a javascript function which will be attached with the onclick event of the Validate Button. Add the javascript like the following:
The lookupValue function finds the control UserNameTextBox on the page and then get its value enterd by user. And the displayResult function writes the final result in the result span on the page. For now I have called the displayResult from lookupValue to test whether it is working or not. The displayResult function will not be called from here. These two functions server the step 1 and step 4 of the client callback process. After the lookupValue had accessed the value from the textbox now we need to call the server side method asynchronously.
Implementing Client Callback functionality on the Server
To implement the client callback on the server side your class must implent the ICallbackEventHandler interface. In our case the Page class is the class which will implent this interface. This interface is used to indicate that a control can be the target of callback event on the server, i.e. a client can call its methods. The interface implents two methods RaiseCallbackEvent and GetCallbackResult.
RaiseCallbackEvent method takes one string argument. This is the method actually called by the client side function and passes the username text box value in the string argument. Once this method prodcues result then GetCallbackResult function is invoked and returns the string produced by RaiseCallbackEvent. GetCallbackResult does not take any argument, and RaiseCallbackEvent returns void. How these methods are invoked is explained in the next section. After implementing ICallbackEventHandler interface your Code behind should look like this.
I have already set up the database connection string and membership in the web.config file. As you can see I have declared a string IsUserExist, which is used as a container for the result generated by RaiseCallback Event method and then returned to the client by GetCallbackResult method. Now we are short one client side function which can call the server method asynchronosly.
Calling the Server Method
Now we need a function which can call the server method asynchronously. W use the GetCallbackEventReference method of the ClientScript property of the Page class in Asp.net 2, and it generates the code to call the server method.
The GetCallbackEventReference method takes five arguments as follows:
1. The reference of the control which has implented the ICallbackEventHandler interface. You do this by providing 'this' keyword in the first parameter. Now the GetCallbackEventReference know that the current class will have a method RaiseCallbackEvent which needs to be invoked.
2. The string value that the client must pass to the server-side method (RaiseCallbackEvent). This will be the value of the username textbox which we have extracted using lookupValue() client side function.
3. The name of the JavaScript function (displayResult) that will be automatically called when the response from the server arrives. When the GetCallbackResult method returns value that value is catched by displayResult client side function's parameter (rValue).
4. The string value that is passed to the dispalyResult function. (This parameter will not be used in this tutorial series.)
5. A boolean value that specifies whether the callback should be done asynchronously. In our case it will be true. Controls like GridView uses synchronous Callbacks.
So how this all is going to work?
GetCallbackEventReference returns a string, which actually will be the content of the function which calls the server side method (RaiseCallbackEvent). The function which calls the server side method will be created in the Load event of the page using RegisterClientScriptBlock method of the ClientScript property of the page. The Page_Load event should look like this:
The names of the arguments that are accepted by the function you are generating ust match the names of the values that you pass to the GetCallbackEventReference method.
RegisterClientScriptBlock registers the function on the page like other javascript functions which you created earlier. Now you need to call the CallServer method, which can be done in a lookupValue function, like this:
See I am calling CallServer function from lookupValue because I need to pass the user name textbox value. You can directly call the CallServer method from the Validate Button textbox, and instead of arg in the GetCallbackEventReference method you can access the value from some server control and use it like ((TextBox)FormView1.FindControl("UserNameTextbox")).Text.
From user name text box to the result span
Note: Read the following steps slowly and review your code after each step.
1. The lookupValue javascript function gets the value from the textbox. Written by you in the script section.
2. The lookupValue function then passes the value of the textbox to the CallServer function. The callserver function is created from the Page_Load event and GetCallbackEventReference was passed as its content.
3. The CallServer function invokes the RaiseCallbackEvent method of the page, with the help of GetCallbackEventReference. The RaiseCallbackEvent takes a parameter arg in CallServer and eventArgument in RaiseCallbackEvent. RaiseCallbackEvent checks for the user and stores a string result in a variable.
4. The result is returned to the client from the GetCallbackResult method, which is invoked by GetCallbackEventReference.
5. The GetCallbackEventReference then passes the result to the displayResult function on the client side, and that function sets the inner html of the result span to the result sent by GetCallbackEventReference.
Conclusion
In this tutorial we discussed that how to get rid of full page postbacks and only updating required areas, by using asp.net 2.0 client call back mechanism. In the next tutorial we learn how to implement following four AJAX patterns using asp.net 2.0 client callback mechanism.
- Predictive Fetch
- Periodic Refresh
- Submission Throttling
- Explicit Submission
References:
The major reference of this tutorial are the chapters 26 to 29 from the book by Dr. Shahram Khosravi, "Professional Asp.Net 2.0 Server Control and Component Development". For detailed and indepth understanding you should consider reading the book.
Implementing ClientCallbacks without Postbacks in ASP.Net web pages
Working with Callback and Control Rendering
Feedback / Query / Suggestion
Sending...