Applying AJAX to your ASP.NET Web Sites Using jQuery

Introduction

With more and more web applications making use of jQuery and AJAX based techniques for communicating with the server, it has become important for any ASP.NET developer to have good grasp of jQuery AJAX techniques that can be used in ASP.NET. AJAX allows you to communicate with the server without requiring full page post back. AJAX requests perform some operation in the background while a user is still working with a page. AJAX techniques not only improve the overall performance of your web application but they can also make your web pages more responsive. jQuery offers a variety of ways to make AJAX calls to the server and this article discusses many of them as applicable to ASP.NET.

Overview of jQuery AJAX Methods

jQuery offers the following ways of making AJAX calls to the server.

jQuery Method

Description

$(“…”).load()

load() method is used to fetch HTML markup from the server dynamically and then set it to the contents of a selected DOM element.

$.get()

$.get() function is used to make generic GET requests to the server.

$.post()

$.post() function is used to make generic POST requests to the server.

$.getJSON()

$.getJSON() function is used to make a GET request to the server and fetch data in JSON format.

$.getScript()

$.getScript() function is used to load remote script files dynamically so that you can execute them further in the code.

$.ajax()

$.ajax() function is a generic function that can be used to make AJAX calls to the server. All the above techniques internally use $.ajax() function to perform their respective operations.

Now that you have brief idea about the AJAX techniques offered by jQuery, let’s discuss each of them one by one. Note that though you will use these techniques in an ASP.NET MVC application, the same jQuery methods can be used in an ASP.NET Web Forms application also.

Sample ASP.NET MVC Application

In order to demonstrate the use of all of the above techniques you will develop an ASP.NET MVC application. The application will simply fetch data from the Customer table of Northwind database using one or the other techniques mentioned above. The Entity Framework data model of the Customer table is shown below:

Entity Framework data model
Entity Framework data model

You can get the data model, controller and views from the code download associated with this article. The application consists of a single controller class – HomeController – that contains in all eight methods. Six of them, viz. Load(), Get(), Post(), GetJSON(), GetScript() and Ajax() are simple action methods and they simply display the corresponding view. The remaining two methods are important ones as they are used by the jQuery AJAX methods mentioned earlier. These two methods are shown below:

public string GetDataAsHTML(string customerId, string format)
{
    NorthwindEntities db = new NorthwindEntities();
    var data = from item in db.Customers
                where item.CustomerID == customerId
                select item;
    Customer c = data.SingleOrDefault();
    string html = "<table border='1' cellpadding='3'>";
    if (format == "row")
    {
        html += "<tr>";
        html += "<td>" + c.CustomerID + "</td>";
        html += "<td>" + c.CompanyName + "</td>";
        html += "<td>" + c.ContactName + "</td>";
        html += "<td>" + c.Country + "</td>";
        html += "</tr>";
    }
    else
    {
        html += "<tr>";
        html += "<td>" + c.CustomerID + "</td>";
        html += "</tr>";
        html += "<tr>";
        html += "<td>" + c.CompanyName + "</td>";
        html += "</tr>";
        html += "<tr>";
        html += "<td>" + c.ContactName + "</td>";
        html += "</tr>";
        html += "<tr>";
        html += "<td>" + c.Country + "</td>";
        html += "</tr>";
    }
    html += "</table>";
    return html;
}
 
public JsonResult GetDataAsJSON(string customerId)
{
    NorthwindEntities db = new NorthwindEntities();
    var data = from item in db.Customers
                where item.CustomerID == customerId
                select item;
    Customer obj = data.SingleOrDefault();
    return Json(obj, JsonRequestBehavior.AllowGet);
}

The GetDataAsHTML() method accepts CustomerID, whose data is to be returned, and display format for the data. Inside it fetches the required Customer and forms an HTML fragment, depending on the format passed (either single row multiple columns or single column multiple rows). The resultant HTML markup is returned to the caller.

The GetDataAsJSON() method accepts a CustomerID and returns a JSON representation of the Customer object under consideration. Notice that the return type of GetDataAsJSON() method is JsonResult. Also notice how a Customer object is being converted to its JSON representation using Json() method. The second parameter of Json() method, i.e. JsonRequestBehavior.AllowGet, indicates that this method can be invoked via GET requests also. We need to set this option because later we will be invoking the GetDataAsJSON() method via GET as well as POST requests.

Using load() to Fetch HTML Markup Dynamically

Normally HTML markup is either placed statically on a page or generated dynamically on the server side. However, at times you may want to fetch HTML markup from the server based on some condition. Consider, for example, the following figure:

Load View
Load View

As shown in the figure, the Load view allows you to specify CustomerID, whose data is to be fetched. The radio buttons control whether the returned data should be displayed in a row or column fashion. In this case the resultant HTML markup of the table displaying the Customer data will change based on the radio button selection. Using the load() method you can achieve this task.

The following markup shows the HTML of Load view:

<body>
  <input type="text"" id="txtCustomerId" />
  <input type="radio" name="format" value="row" />Row
  <input type="radio" name="format" value="column" />Column
  <input type="button" id="btnLoad" value="Get Data"/>
  <br /><br />
  <div id="divData"></div>
</body>

The dynamically fetched HTML is displayed inside the <DIV> element. To load the HTML markup on the fly you will use the load() method of jQuery and call the GetDataAsHTML() method from the controller. The following code shows how:

$(document).ready(function () {
    $("#btnLoad").click(function () {
        var url = '/Home/GetDataAsHTML';
        //var param = "customerId=" + $("#txtCustomerId").val() + "&format=" + $('input:radio[name=format]:checked').val();
        var param = { customerId: $("#txtCustomerId").val(), format: $('input:radio[name=format]:checked').val()};
        $('#divData').load(url, param, function (responseText) {
            alert("HTML loaded successfully");
        });
    });
});

As you can see, the above code calls the load() method on the divData element. The first parameter of the load() method is the URL of the remote resource to be invoked (/Home/GetDataAsHTML in our example), the second parameter represents the parameters required while invoking the remote method. The parameters can be passed in two ways, viz. query string format, JSON format. If you use query string format for parameters, the load() method will make a GET request to the server whereas if you use JSON format, the load() method will make a POST request to the server. In the above example you are sending data in JSON format (for the query string version see the commented line of code). The third parameter is a callback function that is invoked after the remote method completes. The responseText contains the data returned from the server. You can use this function to notify the user or to perform some custom action.

The following figure shows a sample run of the Load view:

Sample Run of the Load View
Sample Run of the Load View

Note that though the load() method is commonly used to fetch HTML markup from the server, you can use it to fetch any string data that you wish to assign as the contents of a DOM element.

Using get() to Invoke HTTP GET Requests

In the preceding example you were interested in loading HTML markup from the server into a DOM element. In many cases, however, you need to fetch the data but you may not want to assign it to the contents of any specific DOM element. Once fetched, you process it in your client script. The jQuery $.get() function allows you to make HTTP GET requests to the server. Optionally you can also pass query string parameters. Typically you will use the $.get() function when data to be passed to the server is small.

The following jQuery code from the Get view shows how $.get() function is used.

$(document).ready(function () {
    $("#btnLoad").click(function () {
        var url = '/Home/GetDataAsJSON';
        var param = "customerId=" + $("#txtCustomerId").val();
        $.get(url, param, function (data) {
            var html = "<table border='1' cellpadding='3'>";
            html += "<tr>";
            html += "<td>" + data.CustomerID + "</td>";
            html += "</tr>";
            html += "<tr>";
            html += "<td>" + data.CompanyName + "</td>";
            html += "</tr>";
            html += "<tr>";
            html += "<td>" + data.ContactName + "</td>";
            html += "</tr>";
            html += "<tr>";
            html += "<td>" + data.Country + "</td>";
            html += "</tr>";
            html += "</table>";
            $("#divData").html('');
            $("#divData").append(html);
        },"json");
 
    });
});

This time you invoke the GetDataAsJSON() method. The $.get() function takes four parameters. The first parameter is the URL of the remote resource to be invoked. The second parameter is the query string to be sent via the GET request. Note that even if you specify the parameter in JSON format it is still converted into its query string equivalent before sending it to the server. The third parameter is a function that is invoked when the data is received successfully. The data can be accessed via data parameter. In our example GetDataAsJSON() method returns a Customer object. Notice how the Customer object is being accessed in the jQuery code. In the above example you are essentially forming an HTML table and then appending it to the <DIV> but you could have performed any other operations on the data. The last parameter of the $.get() function is the type of data returned. The possible values are json, xml, html and script.

Using post() to Invoke HTTP POST Requests

You will use the $.post() function of jQuery to make POST requests to the server. Typically you will go for POST requests when you wish to send a reasonable chunk of data to the server. For example, consider a case where you have a form with many fields and periodically you wish to auto-save the form data in a SQL Server database. In such cases sending data to the server via POST requests is recommended.

The following code shows how the GetDataAsJSON() method is called using $.post() function.

$(document).ready(function () {
    $("#btnLoad").click(function () {
        var url = '/Home/GetDataAsJSON';
        var param = { customerId: $("#txtCustomerId").val() };
        $.post(url, param, function (data) {
            var html = "<table border='1' cellpadding='3'>";
            html += "<tr>";
            html += "<td>" + data.CustomerID + "</td>";
            html += "</tr>";
            html += "<tr>";
            html += "<td>" + data.CompanyName + "</td>";
            html += "</tr>";
            html += "<tr>";
            html += "<td>" + data.ContactName + "</td>";
            html += "</tr>";
            html += "<tr>";
            html += "<td>" + data.Country + "</td>";
            html += "</tr>";
            html += "</table>";
            $("#divData").html('');
            $("#divData").append(html);
        }, "json");
    });
});

Since $.post() function sends data using a POST request, you must represent the data in JSON format as shown above. The parameters of $.post() function and their meaning is almost identical to the $.get() function we discussed in the preceding section.

Using getJSON() to Fetch Data in JSON Format

$.get() and $.post() functions are generic ways to make GET and POST requests to the server respectively. Many times you intend to fetch data specifically in JSON format using a GET request. In such cases the $.getJSON() function of jQuery comes in handy. The $.getJSON() function makes a GET request and returns data in JSON format. If you use query string syntax to represent the parameters it is appended to the request. If you use JSON syntax, it is first converted to a query string and then appended to the request. The following code shows how the GetDataAsJSON() method can be invoked using the $.getJSON() function.

$(document).ready(function () {
    $("#btnLoad").click(function () {
        var url = '/Home/GetDataAsJSON';
        //var param = "customerId=" + $("#txtCustomerId").val();
        var param = { customerId: $("#txtCustomerId").val() };
        $.getJSON(url, param, function (data) {
            var html = "<table border='1' cellpadding='3'>";
            html += "<tr>";
            html += "<td>" + data.CustomerID + "</td>";
            html += "</tr>";
            html += "<tr>";
            html += "<td>" + data.CompanyName + "</td>";
            html += "</tr>";
            html += "<tr>";
            html += "<td>" + data.ContactName + "</td>";
            html += "</tr>";
            html += "<tr>";
            html += "<td>" + data.Country + "</td>";
            html += "</tr>";
            html += "</table>";
            $("#divData").html('');
            $("#divData").append(html);
        });
    });
});

Notice that the $.getJSON() function takes only three parameters because the return type is always JSON. The callback function can be used to process the data returned from the server.

Using getScript() to Load Script Files Dynamically

Normally you specify JavaScript files statically using the <script> tag. However, at times you may need to load script files dynamically based on some condition. Consider a case where you are using JavaScript functions residing in a particular script file only if some condition holds true. Since it is not guaranteed that you will call these functions, you need not load the associated script files in advance. Instead, you can load the script files only if you need to call functions residing in them. In such cases the $.getScript() function can be used.

The $.getScript() function loads a specified script file and then executes it. $.getScript() function is similar to $.get() function with data type set to script. To test $.getScript() function, add a new JavaScript file in the Scripts folder of your application and key-in the following script into it:

function GetCustomerData() {
    var url = '/Home/GetDataAsJSON';
    var param = { customerId: $("#txtCustomerId").val() };
    $.get(url, param, function (data) {
        var html = "<table border='1' cellpadding='3'>";
        html += "<tr>";
        html += "<td>" + data.CustomerID + "</td>";
        html += "</tr>";
        html += "<tr>";
        html += "<td>" + data.CompanyName + "</td>";
        html += "</tr>";
        html += "<tr>";
        html += "<td>" + data.ContactName + "</td>";
        html += "</tr>";
        html += "<tr>";
        html += "<td>" + data.Country + "</td>";
        html += "</tr>";
        html += "</table>";
        $("#divData").html('');
        $("#divData").append(html);
    }, "json");
}

The GetCustomerData() function resides in MyScript.js and makes use of $.get() function to fetch customer data. Now add the following code to the GetScript view:

$(document).ready(function () {
    $("#btnLoad").click(function () {
        var url = '/scripts/myscript.js';
        $.getScript(url, function (responseText) {
            GetCustomerData();
        });
    });
});

As you can see $.getScript() function loads /script/myscripts.js file dynamically. In the callback function you call the GetCustomerData() function. Notice that the GetCustomerData() function resides inside MyScripts.js and not inside GetScript view. If you run the view you will see that the customer data is displayed in a table indicating that MyScript.js has been loaded correctly and GetCustomerData() is available to the view.

Using ajax() to Make AJAX Calls

Now let’s come to the mother of all the techniques you learned so far – $.ajax(). Most of the techniques mentioned so far make use of $.ajax() internally to perform their respective operations. You can call $.ajax() function directly if you need more and precise control on the AJAX request being made. It allows many more options to be configured and is ideal for situations where other techniques fall short of your expectations.

The following code shows how $.ajax() function can be used to call the GetDataAsJSON() server method.

$(document).ready(function () {
    $("#btnLoad").click(function () {
        var url = '/Home/GetDataAsJSON';
        var param = { customerId: $("#txtCustomerId").val() };
        $.ajax({
            url: url,
            type: 'POST',
            data: param,
            dataType: 'json',
            success: function (data) {
                var html = "<table border='1' cellpadding='3'>";
                html += "<tr>";
                html += "<td>" + data.CustomerID + "</td>";
                html += "</tr>";
                html += "<tr>";
                html += "<td>" + data.CompanyName + "</td>";
                html += "</tr>";
                html += "<tr>";
                html += "<td>" + data.ContactName + "</td>";
                html += "</tr>";
                html += "<tr>";
                html += "<td>" + data.Country + "</td>";
                html += "</tr>";
                html += "</table>";
                $("#divData").html('');
                $("#divData").append(html);
            },
            error: function () {
                alert('Error retrieving server data!');
            }
        });
    });
});

The $.ajax() function has many configurable settings. Some commonly used ones are mentioned in the above call. The url option allows you to specify the remote resource URL. The type option allows you to specify the HTTP request type to be used while making the request. In all the other functions discussed earlier you either use GET or POST method. But what if you wish to use PUT or DELETE methods (ASP.NET Web API, for example, needs to use HTTP verbs other than GET and POST). That is where $.ajax() can come handy. The type setting can take the required HTTP request method and send the request using that HTTP verb. The data setting indicates the data to be sent to the server while making the call. The dataType setting governs the data type of the response (XML, JSON, etc.). The success and error functions are used to handle success and error conditions respectively. The success function is where you will process the returned data. The error function will typically flag the error to the user or take some corrective action. The other AJAX techniques allow you to handle success conditions but they don’t give a chance to deal with error condition. If you would like to handle AJAX errors then you need to use $.ajax() function.

If you find yourself using $.ajax() too often in your web application, you can use several helper functions to simplify your AJAX calls. For example, if you are using the same URL in many $.ajax() calls you can use $.ajaxSetup() function as shown below:

$.ajaxSetup({
    url: '/Home/GetDataAsJSON'
});

As you can see, you can use $.ajaxSetup() function to configure settings of all of the subsequent $.ajax() calls. In the above code you use a url setting but you can use other configuration settings also. Another common requirement is to assign a global error handler for all $.ajax() calls. This can be done as shown below:

$(document).ajaxError(function () { alert('Error processing AJAX request!'); });

This way whenever there is any error, the function as indicated by $.ajaxError() will be invoked and you can skip error setting in the individual $.ajax() calls.

Summary

jQuery offers many ways to invoke AJAX requests. This article examined six ways, viz. load(), get(), post(), getJSON(), getScript() and ajax(). Even though all the other techniques make use of $.ajax() function internally, using a specific technique instead of $.ajax() can be handy and quick because many of the settings are pre-configured for you. When you need precise control over an AJAX request being made you can always use $.ajax() directly. Though the examples use an ASP.NET MVC application, the same jQuery methods can also be used in ASP.NET Web Forms applications.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read