Summarizing AJAX Patterns Under ASP.NET
page 5 of 8
by Xianzhong Zhu
Average Rating: 
Views (Total / Last 10 Days): 42047/ 136

The Ajax Framework Pattern

To radically overcome the Ajax related bothering, numerous Ajax frameworks emerge, like bamboo shoots after a spring rain. On the whole, all the Ajax frameworks can be divided into three categories of frameworks: some rely upon the relevant server side techniques, some are based on the client side JavaScript + DOM stuffs and the rest piece the former both together. For various reasons, we herein only touch upon two of the above frameworks: Microsoft ASP.NET AJAX Framework, and a new client-side Ajax framework jQuery.

(1) Using Microsoft ASP.NET AJAX Framework

As for Microsoft ASP.NET AJAX framework, there are a lot stories with it; in this article we are not dwelling upon it, but are going to run directly into the topic. Note in this section we will still bring you a simple sample for the purpose of comparison with the other solutions.

Digging more into the ASP.NET AJAX framework, you will find there are several means to communicate with the server side data. However, the typical mode to consume the server-side data is via Web Services. Below only gives a typical and rough description of the process calling Web Service from JavaScript, as is illustrated in Figure 8.

Figure 8 - The typical process to call Web Service from inside the client side of ASP.NET AJAX framework

The subsequent Figure 9 gives the initial running time snapshot of the sample in this section.

Figure 9

When the user populates something and clicks "Submit," its related click event handler will trigger the Ajax styled invocation of the local Web Service (to be discussed in a minute) passing the entered string. Then, the Web Service method will generate a corresponding short message and return it back to the client side. Finally, if the invocation (in Ajax style) succeeds, the returned data will be rendered on the browser side screen, as shown in Figure 10.

Figure 10 - The server-side message is returned asynchronously and rendered on the screen

Next, let us start the detailed programming from the beginning of writing the Web Service.

Writing the Web Service

Right click the sample website and select "Add new items…" to add a new Web Service "WebService.asmx" to the project. In this case, we will create a simple web method named "HelloWorld."  The following gives the related code.

Listing 9

public class WebService : System.Web.Services.WebService {
public string HelloWorld(string instr) {
    string str = "From the server-side:" + instr + "<br/>Your IP address:";
    str += System.Web.HttpContext.Current.Request.UserHostAddress;//ip
    str += "<br/>The Datatime on the Server side:";
    str += DateTime.Now.ToLocalTime();//
    return str ;

Apparently, method HelloWorld is a common web method without anything peculiar. The point worthy to be noticed is that we have to put an attribute [ScriptService] ahead of the WebService class so as to let ASP.NET AJAX generate for us the client side asynchronous Web Service proxy and further allow us to call the web method directly. As for the web method HelloWorld itself, it simply pieces together several strings concerning the server-side info and then returns it.

Invoking the Web Service from the .aspx Page

First of all, dragging a ScriptManager control onto the sample .aspx page (Default.aspx in our case) is a MUST HAVE whether to write ASP.NET AJAX Server Centric or Client Centric based applications. (NOTE: In Visual Studio 2008, you can directly add an "Ajax Web Form" to simplify this step.) After this, we should also add reference to the Web Service defined above inside the ScriptManager control, so that the ASP.NET AJAX framework can automatically generate the client side asynchronous invocation proxy.

Listing 10

<asp:ScriptManager ID="ScriptManager1" runat="server">
    <asp:ServiceReference Path="~/WebService" />

Next, let us examine how the JavaScript invocation is programmed.

Listing 11

<script type="text/javascript">
    function OnShow(result)
        var s = $get("msg_display");
        s.innerHTML = result.toString();
  function SayHello()//call the server-side web service
        var fs = WebService;
        //invoking the web method
        return false;
<br />
&nbsp;<br />
<br />
<div id="msg_display">
 The server side returned info will be shown here...</div>

Please note the invoking format for the web method SayHello, which is the most important line of code for now because it means, herein, we use the JavaScript in a very easy-to-follow mode to call the client-side proxy generated for the Web Service HelloWorld automatically by the Microsoft Ajax asynchronous communication layer.

Next, method OnShow corresponds to the client side callback function called if the Web Service invocation succeeds. In it, we assigned the returned value from the server side to the innerHTML property of the HTML <div/> element "msg_display." And lastly, if everything goes smoothly, you will see the running time result in Figure 7 and 8.

Here, we have depicted the ASP.NET AJAX pattern in a hurry. As for more concerning the Microsoft Asynchronous Communication Layer and the associated web service proxy, you can refer to the online documents at the official website (

Next, let us switch our topic to another currently hot JavaScript framework jQuery, by which we can also achieve the aim of returning the server-side data asynchronously.

(2)Using jQuery Framework

As a relative latecomer to this world of client-side Ajax libraries, jQuery has taken the web development community by storm, quickly winning the support of major websites. Compared with other JavaScript frameworks, jQuery aims to help designers to leverage their existing knowledge of CSS, XHTML, and good old straightforward JavaScript to manipulate page elements directly, so that they do not need to spend plenty of time juggling the complexities of advanced JavaScript.

Far more than mentioned above, jQuery has also provided the popular Ajax support with concise syntax and rich contents, as well as extensible plug-in support. For brevity, we will not use more words to introduce jQuery. So, for a thorough study and detailed references, you can check out the appended URL's in this article.

Sample 1

Next, let' us look at some Ajax related examples using jQuery. Although the jQuery framework has provided several means to get data from the server side in the asynchronous mode, the simplest way may be using command $.get, whose complete syntax is as follows:


This command will initiates a GET request to the server using the specified URL with any passed parameters as the query string.

Here, we still skip the detailed explanation, but focus upon the example itself. Below gives the HTML code that uses the $.get method.

Listing 12

<script type="text/javascript" src="jquery-1.2.6.js"></script>
<script type="text/javascript">
$(function() {
      //this code is executed when the page's onload event fires
          $('#Button1').click(function() {
                $.get("ajax.aspx", function(response) {
<input id="Text1" type="text" value="Hi,ajax" />
<input id="Button1" type="button" value="Talk to Server 1"/>
<div id="result_panel" ></div>

First of all, we should add reference to the core file of jQuery--jquery-1.2.6.js (the newest version at the time of this writing) at the .aspx file. Then we attach a click event handler to button "Button1," and inside the event function we called the jQuery method $.get. Here, we omit the second parameter of method $.get. In the third parameter (i.e. the callback) we used the jQuery special selector to locate the <div/> element"'result_panel," set its content using the returned value, and finally show it (using the show method). As for the first parameter of method $.get, "ajax.aspx," it is quite similar to the one discussed in the first XMLHTTP+WebForm pattern in this article.

Now you can press F5 to start this sample page (jQueryMode.aspx). With everything smooth and after pressing the button "talk to Server 1," you will get the snapshot as shown in the top part of Figure 11.

Figure 11 - The running time snapshot using jQuery's $.get method

However, to gain the full control of an Ajax request to the server side, you may have to rest upon the $.ajax() method provided by jQuery.

Sample 2

Let us first look at the general syntax of method $.ajax().


This will initiates an Ajax request using the passed options to control how the request is made and callbacks notified. Note the parameter options are of type Object which in fact contains more than ten properties.

Let us still skip the details and see a related sample application. The following gives the key HTML code.

Listing 13

function Button2_onclick() {

        $("#News").html("Loading News......");



            url:"ajax.aspx?msg=" +"Hi",



            timeout: 2000,

            error: function(){

                alert('Error loading HTML document');









<div id='News' style="border-style: outset; border-color:

<input id="Button2" type="button" value="Talk to Server 2"
  onclick="return Button2_onclick();return false;" />

Here, function Button2_onclick contains two sentences: the first is easy to see (which sets the content of the element "News"), the second corresponds to method $.ajax(), which holds several arguments. Here, property type specifies the mode of invoking the HTTP protocol; the url gives the url and related parameters for the request; dataType identifies the type of data that is expected to be returned by the response. The data serves as the query parameters to be passed to the request (If the request is a GET, this data is passed as the query string. If a POST, the data is passed as the request body.). Timeout specifies a timeout for the Ajax request in milliseconds, error is a function invoked if the response to the request returns an error status code and success is a function invoked if the response to the request indicates a success status code.

Now you can launch the sample page to give it a test. The related snapshot is given at the bottom part in Figure 9.

In fact, jQuery provides more powerful and complete Ajax functionalities than the above two samples can hold; however, the more interesting things should be excavated by you, dear readers.

View Entire Article

User Comments

Title: mp   
Name: moosa
Date: 2008-11-12 8:26:44 AM
Title: About Post   
Name: Gopi
Date: 2008-10-15 7:56:44 AM
Useful post..
Title: Very interesting   
Name: Raul Macias
Date: 2008-10-14 2:35:33 PM
Thanks for sharing this; very helpful indeed.
Title: About Post   
Name: Rem
Date: 2008-10-13 2:15:28 PM
Nice post...

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2019  |  Page Processed at 2019-03-24 11:51:53 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search