Getting Data in and out of ASP.NET Applications using Ajax and jQuery – Part I by Dan Wahlin

Web applications have changed a lot over the years. When they first started in the 90's nearly every action a user performed on a page caused the page to fully reload. Full page postback operations were the norm and something that everyone expected.

As the Web matured developers were given additional tools to exchange data with a server such as Remote Scripting, frame tricks, and Asynchronous JavaScript and XML (Ajax) calls. Each of these techniques allowed a page to retrieve data from a server without reloading the entire page. However the only technology that's stuck around is Ajax – it's become extremely popular and is used more and more in modern Web applications.

Ajax is a fairly deceiving name since XML isn't typically used for data exchange between browsers and servers in today's Web applications. It should really be renamed Asynchronous JavaScript and JSON (Ajaj) since JavaScript Object Notation (JSON) data is the standard format used for data exchange by every major browser out there.

What technique should you use to exchange JSON data between a server and a browser? That's the topic of this series of posts.

Ajax and JSON Options for ASP.NET Developers

The .NET framework provides several different techniques that can be used to exchange JSON data between a server and a browser. There are so many options that it can be challenging to know which option is the best and when it should be used. Here's a quick list of a few options for serving up JSON from a server:

1. ASP.NET Web Services (.asmx)
2. Windows Communication Foundation
3. ASP.NET MVC Controller/Action
4. Custom HttpHandler

There's not a "one size fits all" answer to which technology is best but by knowing the different options you can make an educated decision based upon your company's needs. In this first post I'll discuss how ASP.NET Web Services can be used to work with JSON data. Subsequent posts will cover how other .NET technologies can be used.

Using ASP.NET Web Services

ASP.NET Web Services (.asmx) provide a simple and easy way to exchange JSON data with a browser. In fact, you can get a JSON-enabled service up and running in a matter of minutes. Normal ASP.NET Web Services won't do the job, however, because they serve SOAP by default. To JSON-enable a service you need to apply the ScriptService attribute (located in the System.Web.Script.Services namespace) to it. An example of a simple service that provides a GetCustomer operation is shown next:

[ScriptService]
[WebService(Namespace = "http://interfacett.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class WebService1 : System.Web.Services.WebService
 {
     [WebMethod]
     public Customer GetCustomer(int custID)
     {
         //Simulate getting a "real" customer
         return new Customer
                     {
                         CustomerID = custID,
                         FirstName = "John",
                         LastName = "Doe"
                     };
     }
 }
 public class Customer
 {
     public int CustomerID { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
}

A browser can communicate with the service to retrieve a Customer object using custom JavaScript and the XmlHttpRequest object built into browsers or jQuery code similar to the following (jQuery shields you from having to know about how the XmlHttpRequest object works). The call must use a POST operation and define the content type shown below.

<script>
    //Check when the DOM has loaded
    $(document).ready(function () {
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: 'WebService1.asmx/GetCustomer',
            data: '{"custID": 1}',
            dataType: 'json',
            success: function (data) {
                alert(data.d.LastName);
            }
        });
    });
</script>

This example uses jQuery's ajax() function to call the service. I highly recommend jQuery if you're building Ajax-enabled applications that work with dynamic JSON data or any page that requires a lot of DOM manipulation. Once you use it you'll never go back to writing all your JavaScript from scratch since jQuery is designed to be cross-browser by default and lets you focus on your application logic rather than worrying about browser-specific logic. In addition to the ajax() function, jQuery also has get(), post(), getJSON(), and load() functions that can be used to retrieve data from a server. Additional details can be found at http://api.jquery.com/category/ajax.

If you view the request and response sent while calling the ASP.NET service shown earlier in Fiddler (download it here) you'll see the following:

Request:              {"custID": 1}

Response:           {"d":{"__type":"WebApplication4.Customer","CustomerID":1,  "FirstName":"John","LastName":"Doe"}}

You can see that the JSON data defined in the JavaScript sample above is being passed up to the service. However, notice that the response data (also a JSON object) is wrapped with a "d" parameter. This is how ASP.NET Web Services (and WCF services) return data by default. The JavaScript code shown earlier uses the "d" parameter to get to the LastName property:

alert(data.d.LastName);

You can see that setting up and calling a service isn't very difficult at all. The technique can significantly enhance your applications and allow users to load data without reloading an entire page.

Conclusion

In this post you've seen how ASP.NET Web Services can be used to return data to a browser using Ajax and seen how jQuery can be used to call a service. In the next post I'll show how WCF can be used to perform the same type of task.

Part 1: Getting Data in and out of ASP.NET Applications using Ajax and jQuery – Part I by Dan Wahlin

Part 2:Getting Data in and out of ASP.NET Applications using Ajax and jQuery – Using WCF – Part 2

Part 3: Getting Data in and out of ASP.NET Applications using Ajax and jQuery – Using ASP.NET MVC part 3 by Dan Wahlin

Enjoy!
Dan Wahlin
.NET Developer Instructor
Interface Technical Training

 

Posted in Developer Visual Studio / ASP.NET, Web Development | Posted in , , , , , , , , , | 2 Comments

Your Feedback: (2 Responses)

  • Pingback: Getting Data in and out of ASP.NET with ASP.NET MVC – Dan WahlinInterface Technical Training Blog

  • Pingback: Getting Data in and out of ASP.NET Applications using Ajax and jQuery – Using WCF – 2 by Dan Wahlin | Interface Technical Training Blog

  • Leave a Reply

    Your email address will not be published. Required fields are marked *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">