Chapter 15. Using jQuery

The chapter is devoted to the topic of using the jQuery JavaScript library. The jQuery library provides you with a framework that makes it easier to perform common JavaScript tasks. In this chapter, you learn how to use jQuery to select elements from a page, display animations, perform Ajax requests, and use plug-ins.

Overview of jQuery

jQuery is not a Microsoft product. The jQuery library was created by John Resig, who released jQuery under both the MIT and GPL open source licenses. The official jQuery website is located at jQuery.com (see Figure 15.1).

Figure 15.1. The jQuery.com website

image

Although jQuery is not a Microsoft product, Microsoft is including the jQuery library in future versions of the ASP.NET framework (both ASP.NET MVC and ASP.NET Web Forms). The jQuery library is included in the Scripts folder of the Visual Studio ASP.NET MVC template.

Why is Microsoft including jQuery with the ASP.NET framework? jQuery is an extremely popular JavaScript library. It is used by several major websites including Dell, Netflix, and Technorati. Furthermore, jQuery has a passionate and active developer community.

To make it easier to use this popular JavaScript library, the members of the Microsoft ASP.NET team decided to embrace jQuery and treat it much like any other Microsoft product. Microsoft provides “best-effort” product support for jQuery. This means that if you encounter an issue when using jQuery, you can call Microsoft product support and get help.

Note

Because Microsoft does not own jQuery, Microsoft cannot fix bugs in jQuery. Microsoft can submit fixes to the jQuery team just like any other member of the community.

Including the jQuery Library

Before you can use jQuery in your ASP.NET MVC views, you must reference the jQuery library. The Scripts folder includes two versions of the jQuery library:

• jQuery-1.3.2.js

• jQuery-1.3.2.min.js

The first version of the jQuery library is the debug version, and the second version is the release version. The release version is minified; all insignificant whitespace and comments have been stripped to reduce the size of the file. The debug version of the jQuery library is 125KB whereas the release version is (an astoundingly small) 58KB.

While in the process of developing an ASP.NET MVC, you should use the debug version of jQuery to make it easier to find errors. When you are ready to release your application to the world, make sure that you use the release version of the jQuery library.

The view in Listing 15.1 illustrates how you can include the debug version of the jQuery library. The jQuery library is included with the <script src="..."></script> tag.

Listing 15.1. ViewsHomeIndex.aspx

image


Tip

The easiest way to add a script to a view is to simply drag it from the Solution Explorer window onto the code editor.

If you plan to use the jQuery library in multiple views within your ASP.NET MVC application, you should include jQuery within your view master page. That way, you don’t need to add jQuery to each content view individually.

jQuery and Visual Studio Intellisense

Visual Studio is a good JavaScript development environment. When you write JavaScript code in the Visual Studio code editor, you get (partial) Intellisense. This is an amazing accomplishment because JavaScript, unlike languages such as C# or VB.NET, is not a statically typed language.

For example, if you assign a string to a variable, Visual Studio provides Intellisense for all the JavaScript string methods when you use the variable (see Figure 15.2).

Figure 15.2. JavaScript Intellisense

image

Visual Studio not only can provide Intellisense for JavaScript code, Visual Studio also can provide Intellisense for jQuery code. Before you can take advantage of jQuery Intellisense, you need to install a Hotfix for Visual Studio 2008. You can download the required patch from the following location:

http://code.msdn.microsoft.com/KB958502/Release/ProjectReleases.aspx?ReleaseId=1736

The patch modifies Visual Studio so that it retrieves the information required to display Intellisense from either a –vsdoc.js file or a .debug.js file. The –vsdoc.js or .debug.js file must be located in the same folder as the JavaScript library.

For example, if you create a JavaScript library named MyLibrary.js, Visual Studio attempts to retrieve Intellisense information from a file named MyLibrary-vsdoc.js. If the MyLibrary-vsdoc.js file cannot be found, Visual Studio attempts to retrieve Intellisense information from a file named MyLibrary.debug.js. Finally, if neither of these files can be found, Visual Studio retrieves Intellisense information from the actual MyLibrary.js file.

The Scripts folder includes both a jquery-1.3.2-vsdoc.js file and a jquery-1.3.2.min-vsdoc.js file. One file provides Intellisense information for the debug version of jQuery, and one file provides Intellisense information for the release version of jQuery (the minified version).

After you apply the Hotfix, and include the jQuery library in a view, you get Visual Studio Intellisense (see Figure 15.3).

Figure 15.3. jQuery Intellisense in Visual Studio

image

You can download the jQuery -vsdoc.js file from jQuery.com. When there is a new version of jQuery, you need to download the new version of the -vsdoc.js file to get updated Intellisense.

Using jQuery Selectors

One of the most appealing features of jQuery is that most developers, without realizing it, already know how to use jQuery. It transfers the concept of selectors from Cascading Style Sheets into the JavaScript world.

You use selectors in Cascading Style Sheets to select elements from a document and apply a style to the elements. You use selectors in jQuery to select elements from a document and apply a behavior to the elements.

Let’s look at some concrete examples. The following selector retrieves all the DIV tags from a document:

$("div")


The following selector retrieves all the DIV tags that have a CSS class named article:

$("div.article")


And, the following selector retrieves the single element that has an ID of mainContent:

$("#mainContent")


The jQuery library includes additional selectors that you might not be familiar with. For example, jQuery enables you to use filter selectors such as :first, :last, :even, and :odd. The view in Listing 15.2 illustrates how you can use the :odd selector to highlight odd rows in an HTML table to create a banding effect (see Figure 15.4).

Figure 15.4. Using the :odd selector

image

Listing 15.2. ViewsOddIndex.aspx

image


Note

Notice the statement $(pageReady) in Listing 15.2. This statement causes the pageReady() method to execute after the entire document is loaded. If you attempted to execute the code in the pageReady() method before the document had loaded, the code would not work because the HTML table would not have been rendered.

jQuery also supports form selectors like the input, text, password, submit, and button selectors. The view in Listing 15.3 illustrates how you can highlight all the text boxes (input type="text") in a page with a yellow background.

Listing 15.3. ViewsTextIndex.aspx

image


You also can use attributes in a selector by using a selector such as [attribute] or [attribute=value]. The view in Listing 15.4 illustrates how you can retrieve all the anchor tags in a page that point to an external website and add a target="_blank" attribute. (In other words, it forces all links to another website to open a new browser window.)

Listing 15.4. ViewsExternalIndex.aspx

image


In Listing 15.4, the ^= operator is used to match an attribute value that starts with a particular value.

Note

There are more jQuery selectors than described here. You can view the full selector documentation at the jQuery.com website.

Adding Event Handlers

The jQuery library also makes it easy to add event handlers to a set of selected elements. You can use methods like blur(), click(), dblclick(), focus(), hover(), and submit() to create an event handler.

For example, the view in Listing 15.5 contains a menu created with a bulleted list. The hover() method highlights the particular menu item under the mouse.

Listing 15.5. ViewsHoverIndex.aspx

image

image


The view in Listing 15.5 uses the hover() method to set up a function that is called when your mouse moves over a link and when your mouse moves off a link. The functions add and remove a yellow background color (see Figure 15.5).

Figure 15.5. Highlighting menu item

image

Using jQuery Animations

The jQuery library includes three built-in animation effects:

show() and hide()

slideDown() and slideUp()

fadeIn() and fadeOut()

One situation in which these animations are particularly useful is when you need to show progress during an Ajax request. For example, the view in Listing 15.6 contains a link rendered with the Ajax.ActionLink() helper that fetches an updated list of movies. The jQuery slideUp() and slideDown() animation effects are used at the beginning and end of the request.

Listing 15.6. ControllersSlideIndex.aspx (C#)

image


Listing 15.6. ControllersSlideIndex.aspx (VB)

image


The view in Listing 15.6 renders a link and a grid of movies (see Figure 15.6). When you click the link, the jQuery slideUp() animation is invoked. When the Ajax request completes, the jQuery slideDown() animation is invoked.

Figure 15.6. Click the link to see the animation.

image

Notice that the constant "slow" is used with the slideUp() method. You can use the constants "slow", "normal", "fast". Alternatively, you can also supply a millisecond value.

Note

There are an additional set of animations that you can download from the jQuery.com website. The additional animations are part of a separate project named jQuery UI that contains animations with names like Explode, Shake, and Bounce.

jQuery and Ajax

The jQuery library has several methods that you can use to perform Ajax requests:

ajax()—Performs an Ajax request. This low-level method provides you with the most options for performing an Ajax request, but it is more difficult to use than the other methods.

load()—Loads HTML and injects the HTML into an element.

get()—Loads HTML by performing an HTTP GET request.

getJSON()—Loads JSON by performing an HTTP GET request.

getScript()—Loads and executes a script.

post()—Loads HTML by performing an HTTP POST request.

You normally perform an Ajax request to get either a fragment of HTML from the server or JSON data from the server. The jQuery library enables you to easily perform either type of request.

For example, the view in Listing 15.7 updates a news item every 3 seconds (see Figure 15.7). The news item is retrieved with the jQuery load() method.

Figure 15.7. Random news item

image

Listing 15.7. ViewsNewsIndex.aspx

image


In Listing 15.7, the jQuery load() method invokes the Refresh action of the News controller by requesting the URL /News/Refresh. The News controller is contained in Listing 15.8.

Listing 15.8. ControllersNewsController.cs (C#)

image


Listing 15.8. ControllersNewsController.vb (VB)

image


The News controller Refresh() action randomly returns one of two partials. The Refresh() action either returns the News1 or the News2 partial. Each partial contains a different news item. For example, the News1 partial is contained in Listing 15.9.

Listing 15.9. ViewsNewsNewsNews1.ascx

image


The view in Listing 15.7 uses jQuery to retrieve a fragment of HTML across the wire. Instead of using jQuery to return a fragment of HTML, you can use jQuery to return JSON data.

For example, the view in Listing 15.10 displays a random set of movie records from the movie database table (see Figure 15.8). The movie records are retrieved with the help of the jQuery getJSON() method.

Figure 15.8. Displaying random movies with Ajax

image

Listing 15.10. ViewsMovieIndex.aspx

image

image


Warning

Notice that the jQuery ajaxSetup() method is called in the pageReady() method to disable browser caching. If you do not disable browser caching, Internet Explorer always displays the exact same news items.

The getJSON() method invokes the controller action mapped to the URL /Movie/Refresh and, after the data is returned, the method calls the showMovies() method. The showMovies() method creates a bulleted list of the movies returned from the server. The bulleted list is assigned to a DIV tag named divMovies.

The movies are retrieved from the Refresh action exposed by the Movie controller in Listing 15.11.

Listing 15.11. ControllersMovieController.cs (C#)

image

image


Listing 15.11. ControllersMovieController.vb (VB)

image


The Refresh() method returns a set of three movies randomly retrieved from the movies database table. The Json() method is used to return a JSON result. The JSON result looks like this:

image


The advantage of using JSON over fragments of HTML is that JSON enables you to represent information much more compactly. In other words, in most cases, using JSON results in better performance.

Using jQuery Plug-Ins

The jQuery library was designed to be small. It contains only the essentials for building JavaScript applications. You don’t want the users of your website to wait while downloading a JavaScript library that contains functionality that is never used.

If you want to do something more specialized, you can download a jQuery plug-in. There are hundreds of plug-ins available for download from the jQuery.com website (see Figure 15.9). These plug-ins enables you to accomplish an amazing variety of programming tasks, including plug-ins that display light boxes for images, plug-ins that render fancy menus, and plug-ins that enable you to copy data to the clipboard. You can download these plug-ins from http://plugins.jQuery.com.

Figure 15.9. jQuery plug-ins available for download

image

The jQuery library was designed to make it easy to use plug-ins. In this section, we discuss how you can use something called the tablesorter plug-in. This plug-in enables you to sort the columns of an HTML table.

Note

You can download the tablesorter plug-in from http://tablesorter.com. The tablesorter plug-in is also included in the Visual Studio project that corresponds to this chapter. The tablesorter plug-in is dual licensed under the MIT and GPL open source licenses.

The view in Listing 15.12 uses the tablesorter plug-in. When you click one of the table headers—Id, Title, Director, DateReleased—the rows in the table are sorted by that column (see Figure 15.10). If you click the same header more than once, the sort order is reversed.

Figure 15.10. Using the tablesorter plug-in

image

Listing 15.12. ViewsSortIndex.aspx

image

image


To use the tablesorter plug-in, you need to do only two things. First, you need to include the tablesorter plug-in in the page. In Listing 15.12, the tablesorter is included with the second <script src=""></script> tag.

Second, you need to call the tablesorter() method on the table, or tables, that you want to sort. In Listing 15.12, the tablesorter() method is called in the pageReady() method.

Warning

The tablesorter plug-in will work only with an HTML table that includes <thead> and <tbody> tags. The HTML table generated by the Visual Studio scaffolding does not include these tags. Therefore, you must add the <thead> and <tbody> tags by hand.

Summary

In this chapter, you were introduced to the jQuery JavaScript library. You learned how to use the jQuery library to select elements, create event handlers, display animations, and make Ajax calls. You also learned how to use jQuery plug-ins to extend the functionality of the base jQuery library.

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

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