In September 2008 Scott Guthrie, the head of the ASP.NET team, announced in a blog post that Visual Studio would be shipping with the jQuery library. He writes:
With that, JQuery is officially embraced by ASP.NET.
A brief introduction of JQuery
mytable with alternative color for every other row, you can simple do this in jQuery.
Listing 1: jQuery code for making a zebra-style table
The magic dollar sign ($) and a chain of operations
In jQuery, the most powerful character / symbol is the dollar sign. A
$() function normally returns a set of objects followed by a chain of operations. An example
Think of it as a long sentence with punctuations. Indeed it is a chain of instructions to tell the browser to do the following:
- Get a div with class name is test;
- Insert a paragraph with class name is quote;
- Add a little text to the paragraph;
- Operate on the DIV using a predefined method called fadeout.
So there it is, the first two basics:
$() and chainable.
JQuery uses CSS selectors to single out one element or a group of elements, and normally we use a combination of them to target specific elements. For example:
$(‘p.note’) returns all
<p> elements whose class name is note;
$(‘p#note’) returns the
<p> element whose id is note;
$(‘p’) returns all
To select a child or children, we use the right angle bracket (>), as in
$(‘p>a’) (returns all of the hyper links within the
To select element(s) with certain attributes, we use , as in
input[type=text] (returns all text input element);
To select a container of some other elements, we use has keyword, for example:
$(‘p:has(a)’) (returns all
<p> elements that contains an hyperlink);
jQuery also has a position-based selector for us to select elements by position, for example
The most commonly used command in jQuery is
Document.Ready(). It makes sure code is executed only when a page is fully loaded. We often place code blocks inside this
Document.Ready() event. For example:
So far, we have brushed upon a bit of the core jQuery library. The true power of jQuery lies in its speed and flexibility and extendibility, and the ever-growing however already immense collection of jQuery plugins that deal with tasks big and small. As of today, by the tally of jQuery.com, there are 1868 plug-ins, including 100 in AJAX, 123 in Animation and effects, 66 in data, 321 in user interface. After all, JQuery is designed to be small and nimble, providing only the core functionalities required in the most common scenarios, and make others available only when needed and serve in the form of a plug-in.
ASP .NET and JQuery
Long gone is the era when most computing was done on a desktop, when web pages were more or less like virtual bulletin board. Now the impatient and internet-saturated generation is insatiable with substance, dynamics and connectivity. They want rich content, dazzling visual and instant feedback. More than ever, web development has become a tight coordinated dance between server and client. The server does the heavy lifting in the background, processes requests, churns up data and passes it back to the requesting client; from which point the client computer takes over. Interactions now taken place between web and user would be taken care by client side script, and web server would only be involved when client initiates a new request for data operation. The introduction and adoption of AJAX (the technique of performing asynchronous requests through client scripts) is fueled by and fuels this trend.
While AJAX is now the unifying technique across browsers (IE or Firefox), platforms (PC or MAC) and languages (C# or Java or PhP), it did not launch onto this popularity train until just a few years ago, when Google showcased its power with an array of applications. So with Google maps, Gmail, Google news, AJAX becomes the gold messenger of server and client communication. As if overnight, more than 100 AJAX libraries sprung up to simplify and smooth this process.
On the other hand, ASP .NET has always been predominantly a server side technology, web services and code behind page methods have always been the founding stones of web applications. The development of ASP .NET AJAX helps developers to easily make service calls from client side script.
Let’s take a look at how we can use jQuery to consume ASP .NET web services and page methods.
Consuming ASP .NET web services using jQuery
From the conception to now, web services has gone a long way. Web services use XML as the default data exchange format and SOAP as its protocol. However it has long been dogged by complaints of complexity and lack of open standards. XML as its default message format often feels cumbersome and bandwidth-heavy.
Tailored to accommodate this trend, data returned from ASP .NET web script services are by default in JSON format.
JSON serialized web service
The following is a dummy ASP .NET web service. Please note that this service is adorned with the
Listing 2: A Dummy web service
If we call the method
sayHello and then use Firebug for Firefox to check the server response, it would look like this:
A call (
POST) to ASP .NET JSON-serialized web services must meet two criteria:
- It must carry a HTTP Content-Type header with its value set to
- It must be called via the HTTP POST verb or else the request would be rejected. To submit a GET request, we just need to submit empty data string.
Consuming a web service using ASP .NET AJAX
It is easy to call web services with the native ASP .NET AJAX, which would automatically take care all of the gritty details. It takes two steps:
First, add a
ServiceReference to the
ScriptManager control in the web form, as such:
Second, call any web methods defined in the web service by passing the necessary parameters and a callback function. The callback will be invoked once the data is returned from server. The following is a complete example of how we call a web service using ASP .NET AJAX.
Listing 3: Calling a web service using ASP .NET AJAX
However as we have mentioned before, ASP .NET AJAX is rather heavy-handed and carries hefty performance penalties. In comparison, jQuery is superior in its promise of “less code do more”.
However how do call ASP .NET web services using jQuery?
Consuming a web service using jQuery
The answer: use the jQuery command
ajax with the following syntax:
It looks deceivingly simple. However, you can stuff a lot of specifics in this umbrella parameter
options, such as the required ones: url of the web service (
url), request content type (
contentType), response data type (
dataType), callback function for success (
success); and the optional ones: callback function in case of failure (
error), a timeout for the AJAX request in milliseconds (
For example, we can call a specific web method in a web service as such.
Listing 4: JQuery .ajax command
Two things are worth noting in the above JQuery AJAX call. First, we must specify the contentType’s value as
application/json; charset=utf-8, and the
json; second, to make a
GET request, we leave the
data value as empty.
So put it together, the following code demonstrates how we would use JQuery to call the web service we created above.
Listing 5: Calling a web service using jQuery
Calling an ASP .NET page method
In terms of AJAX calls, a page method and a web service are almost interchangeable. Page methods, as the name suggests, is page dependant. Rather than creating a stand-alone web service, you can simple code a server-side method for data fetching and processing and call it from your client-side script.
Here is how.
A dummy page method
The following is the code sample of a dummy page method that takes no parameters
Listing 6: A dummy hello world page method
Please note that page methods must be declared as static, meaning a page method is completely self-contained, and no page controls are accessible through the page method. For example, if you have a textbox on the web form, there is no way the page method can get or set its value. Consequently any changes with regards to the controls have no affect on the page method. It is stateless and it does not carry any of the view-state data typically carries around by an asp .NET page.
Calling a page method from jQuery
We use the same jQuery command
$.ajax to call a page method, as shown in the following example.
In ASP .NET, server side controls can be bound to a data source. Those controls are essentially presentation templates. Many web applications have more or less abandoned the server-centric programming model of ASP .NET. As a result, we have to retake up the tasks of doing our own plumbing, of iterating through data and stuffing it in the right slot.
So for example, if we want to populate a table with data obtained from a web service, without a proper template, we have manually iterate through records and weave all of the data into a long string, peppered with events.
Let’s say we have a web service that returns a CD catalog, as such:
To display the data in a table, we might do the following
Listing 7: Data presentation without a template
How to use jTemplate
A much better alternative is that we use a template engine. jQuery has a few template plugins, the most widely accepted is jTemplate. jTemplate is a JQuery template engine that works with AJAX and JSON data. We can use Jtemplate in the following steps:
Second, define your template:
Please note that we define the template in a script block, which can be accessed by its id; also,“jTemplates uses python like syntax and the $T is a reference to the data item passed to the template. Data can be passed in as an object and you can reference the object’s properties off this $T data item.” (Rick Strahl)
Third, call your web service in your script, designate the template and instantiate it with data.
Figure 4: Using jTemplate to display a CD catalog
ASP .NET client templating engine
In July 2008, the ASP .NET team also announced its own client template engine, as blogged by Bertrand Le Roy. It uses
The following is how we can populate an ASP .NET client template engine with the data we get from the above CD catalog web service.
Listing 8: ASP .NET AJAX client templating engine
As we can see, the ASP .NET client template engine is very simple and elegant. However, it is still at its early stage. The template is still lacking in flexibility and it still waits to be widely tested and accepted by the developers community.
Web developer, Data Analyst, GIS Programmer
This author has published 12 articles on DotNetSlackers. View other articles or the complete profile here.
You might also be interested in the following related blog posts
File Upload using jQuery AJAX in ASP.NET Web API
jQuery Typewriter Effect on HTML Text
HTML Input Value Trimming using jQuery
Internationalization using jquery.i18n.properties.js
MVC using Web API and JQuery to GET or POST Data
Complex Jquery Datatable with Database State Saving & Basic Use of jQuery Templates with ASP.NET C# 4.5, Entity Framework
Calling A Webmethod Using Jquery Ajax
ASP.NET Repeater with jQuery Slider
With jQuery and ASP.NET MVC Almost Radio Buttons
IE XML5633 Error when using jQuery.parseXML()
Please login to rate or to leave a comment.