Published: 08 Feb 2009
By: Xun Ding
Download Sample Code

A brief introduction to jQuery and ways in which we can integrate it into ASP .NET

Contents [hide]

Introduction

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:

“jQuery is a lightweight open source JavaScript library (only 15kb in size) that in a relatively short span of time has become one of the most popular libraries on the web. A big part of the appeal of jQuery is that it allows you to elegantly (and efficiently) find and manipulate HTML elements with minimum lines of code … There is a huge ecosystem and community built up around JQuery. The jQuery library also works well on the same page with ASP.NET AJAX and the ASP.NET AJAX Control Toolkit.”

With that, JQuery is officially embraced by ASP.NET.

A brief introduction of JQuery

jQuery is the star among the growing list of JavaScript libraries. A few of its characteristics are light-weight, cross-browser compatibility and simplicity. A common task that sometimes takes 10 lines of code with traditional JavaScript can be accomplished with jQuery in just one line of code. For example, if you want to dress up a table with an ID 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:

  1. Get a div with class name is test;
  2. Insert a paragraph with class name is quote;
  3. Add a little text to the paragraph;
  4. Operate on the DIV using a predefined method called fadeout.

So there it is, the first two basics: $() and chainable.

jQuery Selectors

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 <p> elements

To select a child or children, we use the right angle bracket (>), as in $(‘p>a’) (returns all of the hyper links within the <p> element);

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 $(‘p:first’)

Document.Ready()

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.

jQuery is one of the more effective and light-weighted ones. ASP .NET team has come up with its own AJAX and JavaScript libraries in its unifying ambition to convert every programmer (be it C# or VB or something else) into a Microsoft faithful. However, its JavaScript library is considerably bulky, bandwidth-costly and poses a steep learning curve.

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.

However, with AJAX, JSON overtook XML as a more efficient alternative. It retains all of the advantages claimed by XML, such as being readable and writable for humans, and easy to parse and generate. JSON, though completely language independent, borrows a lot of conventions from languages such as C, C++, C#, Java, JavaScript, Perl, Python, etc. This makes JSON an instant hit among programmers.

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 ScriptService attribute that makes it available to JavaScript clients.

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 (GET or 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 application/json
  • 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 (timeout), etc.

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 dataType as 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.

Client Templating

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:

First, download the JQuery JavaScript file and reference it in your web page:

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

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 {{expression}} as place holder for data, it works with JavaScript and AJAX. The ASP .NET client template engine also allows live bindings (dynamic data refreshing and updates). For more information, please read Using client templates, part 2: Live Bindings.

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.

Summary

With the marching forward of AJAX to the forefront of building rich interactive web sites, jQuery as the lightweight yet powerful JavaScript library also gains ever more prominence. In late 2008, Microsoft ASP .NET officially partners with jQuery to develop better and more efficient approaches to speed and smooth the communication between servers and client. Reflecting on the trend of harnessing the best of the web, this article paints in broad strokes some of the characteristics of jQuery and how we can integrate jQuery into ASP .NET.

References

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Xun Ding

Web developer, Data Analyst, GIS Programmer

This author has published 12 articles on DotNetSlackers. View other articles or the complete profile here.

Other articles in this category


Animating a Web Form using ASP.NET AJAX
In this article you will learn how to animate a webform using asp.net ajax.
Jquery Ajax
JQuery makes communicating with the server very, very easy. JQuery uses get(), getJSON(), and post(...
jQuery Deferred Objects Promise Callbacks
jQuery Deferred/Promise objects untangle spaghetti-like asynchronous code.
jQuery in Action 2nd edition: Queuing functions for execution
This article is taken from the book jQuery in Action, second edition. This segment shows how you can...
Test120Jan
This is my custom article

You might also be interested in the following related blog posts


Big n Bulky "How To" Document for ASP.NET MVC, Entity Framework, LINQ, HTML 5 and JQuery read more
ASP.NET Gridview with Row Drag and Drop using Jquery TableDnD read more
Attaching to Telerik MVC Grids Client Event using jQuery read more
MVC and jQuery with WCF Data Service read more
Freeze Gridview Header Using JQuery read more
Calling WCF Services with jQueryStripped Down read more
File Upload using jQuery AJAX in ASP.NET Web API read more
jQuery Typewriter Effect on HTML Text read more
HTML Input Value Trimming using jQuery read more
Internationalization using jquery.i18n.properties.js read more
Top
 
 
 

Discussion


Subject Author Date
placeholder Thank you ! Henri Black 6/1/2009 9:47 AM
getting error Fahad Ahmed 6/12/2009 2:16 AM
placeholder Excellent article Shalan Naidoo 6/21/2009 7:41 PM
Should have read your before writing mine Yoav n 6/27/2009 2:30 PM
placeholder very informative Gaurav Bhatt 4/19/2010 3:57 AM
Interesting but... Alan Fry 10/22/2010 11:51 AM
placeholder I liked this article Pradip Bobhate 3/11/2011 2:18 PM
which one is best way to use jquery? Rajesh Chekuri 8/7/2012 12:55 AM
placeholder image fetching from database Nasrin Ghasempoor 3/6/2013 4:32 AM
AjaxDataControls Sonu Kapoor 2/9/2009 10:02 PM
placeholder thanks Xun Ding 2/10/2009 3:28 PM
Very Good Article Shailendra Singh Chauhan 3/19/2009 3:52 PM
placeholder Thanks for the compliment Xun Ding 3/19/2009 3:58 PM
Interesting article Richard Ruth 3/20/2009 11:15 AM
placeholder RE: Interesting article Xun Ding 3/20/2009 11:35 AM
RE: RE: Interesting article Richard Ruth 3/20/2009 11:43 AM
placeholder RE: RE: RE: Interesting article Xun Ding 3/20/2009 12:03 PM

Please login to rate or to leave a comment.