Chapter 40. Client-Side Ajax with jQuery

In this chapter, you learn how to build “pure” Ajax applications that execute on the browser instead of the server. In previous versions of ASP.NET, the primary method of writing client-side code was to use the Microsoft AJAX library. This library provided extensions to JavaScript to make it resemble .NET languages such as C# and VB.NET.

The corporate vice president of .NET Platform, Scott Guthrie, announced in March 2010, that it was taking a different approach to client-side development. A JavaScript library called jQuery is now the recommended method to build client-side functionality. In ASP.NET 4, you can still use the Microsoft AJAX library to develop client-side applications, but it is now part of the Ajax Toolkit instead of built into ASP.NET Framework.

In the first part of this chapter, you learn about the jQuery library and how it works. You dive into two core features of jQuery: events and selectors. You also build your first application that executes completely on the client-side.

Next, we get to the heart of client-side Ajax. You learn how to perform Ajax calls from the browser to the server. You learn how to call both web methods exposed by an ASP.NET web service and web methods exposed by an ASP.NET page.

What Is jQuery?

jQuery is an extremely fast, lightweight JavaScript library that simplifies many aspects of client-side web development. You can use jQuery for almost any client-side functionality that you can think of—event handling, animations, drag-and-drop functionality, asynchronous web service calls, and much more. Furthermore, jQuery supports a robust plug-in model that enables developers to write their own extensions to implement whatever functionality they want. There are already hundreds of powerful jQuery plug-ins available.

jQuery is CSS3-compliant and works on almost all browsers—Internet Explorer 6.0+, FireFox 2+, Safari 3.0+, Opera 9.0, and Google Chrome. This means that you can write one set of code and not have to worry about handling the specifics of different browser implementations; each line of jQuery works exactly the same on all browsers.

The jQuery library is used on an incredible number of popular websites. Google, Dell, Bank of America, Digg.com, Netflix, WordPress, and even the White House are some examples of websites that rely on jQuery for client-side functionality.

Using the jQuery Library

The supporting code for jQuery, is contained in a single JavaScript file named jquery-<version>.js. At the time this book was written, the latest jQuery version is 1.4.1, so the filename is jquery-1.4.1.js. This file is included automatically in the Scripts folder when you create a website project using the ASP.NET Website template in Visual Studio 2010.

You’ll also see two other files in the Scripts directory—jquery-<version>.min.js and jquery-<version>-vsdoc.js (see Figure 40.1).

Figure 40.1. The jQuery library files within an ASP.NET project.

image

The “min” file is a “minified” version of the jQuery library. It can be compared to the two different versions of .NET builds: Debug and Release. The Debug contains more information so that you can track down errors but is ultimately slower. Similarly, the minified version of jQuery is a lot faster but is unreadable for debugging purposes. The minified version of jQuery is only 24KB, whereas the development version is 155KB—more than six times the size. For production applications, you should use the minified version of jQuery. For all the following examples, we use the larger, slower developer version of jQuery so that you can debug the applications.

Note

The Microsoft AJAX libraries also have separate development and minified versions. The minified version is 83KB—more than three times the size of the minified version of jQuery!

The vsdoc file provides jQuery IntelliSense within Visual Studio. Visual Web Developer attempts to provide all jQuery methods and objects in the pop-up window as you write your JavaScript. This is quite an accomplishment considering that jQuery (and JavaScript, in general) is dynamic, and a variable might change its data type at any time at runtime.

It is easy to add jQuery to any web page. You need to add only one line of HTML:

<script type="text/javascript" src="./Scripts/jquery-1.4n.1.js"></script>

Simply add this to your page, and you have the full jQuery library available to you. You don’t need to explicitly add a reference to the vsdoc file—as long as the filename matches the jQuery filename up to the -vsdoc.js, the IntelliSense file will be interpreted automatically (see Figure 40.2).

Figure 40.2. Adding jQuery to a page and jQuery IntelliSense.

image

Creating a jQuery File

Before we do anything else, we need to discuss how you create an external JavaScript file and reference it in a Web Form page. Although you can add JavaScript directly to a page by wrapping it in <script> tags, it is better to separate your client-side logic into its own file. You create a JavaScript file by selecting Website, Add New Item and selecting the Jscript File option (see Figure 40.3).

Figure 40.3. Creating a script file with Visual Web Developer.

image

For example, the file in Listing 40.1 contains a single JavaScript function called sayMessage() that displays a JavaScript alert with a message.

Listing 40.1. myScript.js

images

By default, Visual Studio will put this file in the root of your website. To keep things organized, you should move this file in the “scripts” folder of your project.

You should notice two special things about this file. First, at the bottom of the file is a call to a jQuery method: $(document).ready(). The significance of this method is explained in the next section.

Second, you notice a comment at the top of the file that references the jQuery library. This reference gives you full jQuery Intellisense in your JavaScript file, even though the jQuery library isn’t explicitly referenced in your actual JavaScript code.

After you create an external JavaScript file, you can use it in an ASP.NET AJAX-enabled page by creating a script reference. The page in Listing 40.2 illustrates how you add a script reference to the myLibrary.js library.

Listing 40.2. HelloJquery.aspx

images

You can see that all we’re doing is adding another script reference to our new myScript.js file. Other than that, we’re not adding any additional code to the page. From this simple six-line script and the reference to it, we’re already adding client-side functionality to our page.

The $ Method and $(document).ready()

The heart of jQuery lies is a single method called jQuery(). To make things easier for developers, the same method can be called by using the $ character. The dollar-sign is a valid character in JavaScript, so it alone can be used as a method name.

The $() method is used to select objects in your web page. In general, it is similar to the JavaScript method getElementById, except it’s much more flexible. We cover selectors in detail in the next section, but for now, understand that the $() method is used in every jQuery method.

The $(document).ready() call that we used in the previous example is your first example of a jQuery event. jQuery events are similar to ASP.NET events because they fire at certain points during an application’s execution. The $(document).ready() event fires when the Domain Object Model (DOM) is loaded. Generally, you can put most of your jQuery code in this event:

image

By doing so, you’re ensuring that your page is ready before it runs your code. Otherwise, your logic might start executing before the page has completed loading, and your code might not work as expected.

In Listing 40.2, our script tells the browser to execute the sayMessage() method when the document is ready. When you execute the page, you can see the alert box pop up as soon as you open the page. Although it appears to pop up right away, the browser is actually waiting until any other page-preparing logic has completed and is ensuring that the DOM is fully loaded. When those conditions are met, the code in $(document).ready() fires and you see the alert box.

jQuery Selectors

Selectors are a core piece of the jQuery library. jQuery code follows this basic methodology:

Select an element.

Do something with it.

As we mentioned above, the $() is the method that you use to select elements. For $(document).ready(), we’re actually selecting the “document” and defining what to do when the ready() event fires.

You can select any element (or multiple elements) on your page. Following are three basic ways of selecting elements:

By IDMatches a single element with the element ID. The ID you provide should be prefaced by a # character. For example, $("#myId") would match <div id="myId">.

By CSS ClassMatches all elements with the provides CSS class. The class you provide should be prefaced with a . character. For example, $(".navigationListItem") would match <li class="navigationListItem">.

By ElementMatches all elements by tag name. For example, $("div") would match <div id="myId1"> and <div id="myId2">.

After selecting an element (or elements), you need to do something with it. For example, you can define what should execute when you click an element by using the "click" function. Listing 40.3 demonstrates this:

Listing 40.3. jqueryClick.js

images

This code has two sections of jQuery. First, we define a function called "spanClicked" that selects the element with the ID "colorSpan". It then adds a CSS class to that element called "redClass" Second, we define the $(document).ready() code. When the document finishes loading, we select the element with an ID of "clickSpan" and tell it to execute the "spanClicked" function whenever that element is clicked.

Notice how we use inline function() syntax in the $(document).ready code. This is called an anonymous function in JavaScript and enables you to define functions inside of your logic without needing to explicitly define and name it. It is often used with jQuery and enables you to nest all your logic in a single call instead of defining a method for each one. It dramatically improves the readability and fluidity of your code as well.

The page in Listing 40.4 defines the span elements along with the CSS class and demonstrates the jQuery selectors.

Listing 40.4. jqueryClick.aspx

images

There is an amazing amount of events and functions available in jQuery to apply to your selected objects. For a complete list, visit the documentation and tutorial sections at http://www.jquery.com.

Calling Web Services from the Client

The heart of Ajax is the capability to send and retrieve information from the web server without needing to post back a page to the web server. Ajax is all about performing “sneaky” postbacks.

The vision behind a pure Ajax application is that it should consist of a single page. All updates to the single page after it has been loaded should be performed by calling web services. You should never need to perform a postback because any postback results in a bad user experience. (The page jumps and the universe freezes.)

The jQuery library provides support for calling web services directly from the client (the web browser) with a built-in function called $.ajax. In this section, you learn two methods of exposing a web method to an AJAX page. You learn how to call a web method from a separate web service and how to call a web method exposed by the page.

Calling an External Web Service

Let’s start simple. We create a Quotation web service that randomly returns a quotation from a list of quotations. Next, we create an AJAX page that contains a button. When you click the button, a random quotation displays in a <span> tag (see Figure 40.4).

Figure 40.4. Retrieving a random quotation from the server.

image

The first step is to create the web service, which is contained in Listing 40.5.

Listing 40.5. QuotationService.asmx

images

You create the file in Listing 40.5 by selecting Website, Add New Item and choosing the Web Service item.

The web service contains a single web method named GetQuote(). This method returns a single quotation from a list of quotations as a string.

There is only one thing special about this web service. A ScriptService attribute is applied to the web service class. (The ScriptService attribute lives in the System.Web.Script.Services namespace.) You must add this attribute to call the web service from an AJAX page.

Now that we have created the web service, we can call it from an AJAX page. The page in Listing 40.6 calls the web service to display a random quotation.

Listing 40.6. ShowWebServiceMethod.aspx

images

images

You should note several things in this page. To begin, the first thing we do in the $(document).ready() call is add a click event handler to the "btnGet" element. This click event makes one function call to the $.ajax function.

The $.ajax jQuery function makes an asynchronous call to a URL. In this case, we call the web service method that we defined at QuotationService.asmx/GetQuote. If this asynchronous call is successful, the “success” parameter’s function gets called, which selects the “spanQuote” and fills it with the data that was returned by using the “html” jQuery function.

We also pass in a data type and content data type of “json” to our web service. JSON stands for JavaScript Object Notation and is a lightweight format that enables you to define an unordered set of name/value pairs. This data is contained in the "d" property of data—when we call the "html" jQuery function, we pass in "data.d" as the parameter so all the data is pushed into the span. When web services first started being utilized, XML was used almost exclusively to send data back and forth. Today, JSON is quickly becoming the standard because large amounts of data can be sent back and forth without the extra overhead of XML.

When you call a web method with $.ajax, you can pass a reference to both a success and an error method. If the web method call is successful, the success method is called. Otherwise, the error method is called.

In Listing 40.6, if the $.ajax call is successful, the quotation displays in a <span> tag in the body of the page.

Calling a Static Page Method

If you do not plan to call a web method from multiple pages, don’t perform all the work of creating a separate web service. Instead, you can expose a static method from the same AJAX page calling the web method.

For example, the page in Listing 40.7 includes a server method named GetQuote().

Listing 40.7. ShowPageMethod.aspx

images

images

Just like in the previous section, you can call a page method in the exact same manner as a web service. We pass in the URL and method name of our GetQuote() method to the $.ajax call, and our success and error references do the rest. This is handy when you develop page-specific functionality that doesn’t require the extra work of building a separate web service.

Summary

In the first part of this chapter, you learned about the jQuery library and what it has to offer. You learned about the $(document).ready() event and how to select elements with the $() jQuery function.

In the next part, you learned how to call web services from the browser. You learned how to call a web method in an external web service and a static web method exposed from a server-side page.

jQuery is a powerful tool that makes it incredibly easy to add client-based functionality to your web applications with little code. We have barely scratched the surface of what jQuery can do—it is a great way to improve the user experience of your applications, so spend some time to learn everything it has to offer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset