Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

A Gentle Intro To jQuery in ASP.NET

As an ASP.NET developer, you probably often hear about "jQuery" term. Although jQuery is not strictly part of ASP.NET, it is very popular among ASP.NET developers and used in many ASP.NET web sites.

What is jQuery

jQuery is JavaScript library, originally written in 2006. by John Resig, and today supported by jQuery team.

 

The purpose of jQuery is to make JavaScript development easier and faster. jQuery is browser independent, so your code will work correctly in all popular web browsers. jQuery is open source and free.

jQuery slogan "Write less, do more" sounds very appealing, and today jQuery is widely used on big and small websites worldwide and recognized as most popular JavaScript library.

Why use jQuery

jQuery is just JavaScript, so everything possible with jQuery could be done with plain JavaScript too. Theoretically, you can create JavaScript code which will execute faster than jQuery and do exactly what you want. But, in practice, there are many hard and tedious problems that you can experience if you use plain JavaScript.

First advantage of jQuery is that it simplifies common tasks. If some feature is already created, working well and is tested on many websites, then there is no reason to create it again from scratch.

One more big advantage of using jQuery (or some other similar JavaScript library in general) is cross browser compatibility. If you are ever coded in plain JavaScript, then you know how difficult could be to achieve same functionality in FireFox, Chrome and Internet Explorer. Sometimes, code works in one version of Internet Explorer but returns an error in older or newer version etc. It is not very interesting to spend time on testing same code in many different browsers, just because web browsers' creators were sloppy and don't care about web standards.

Unlike plain JavaScript, jQuery is "JavaScript development as it should be". jQuery syntax is simple for developer, you don't need to care much about compatibility. Inside of library, encapsulated logic takes care about different web browsers and their incompatible versions.

Problems commonly solved by using jQuery

jQuery is often used:
  - in creation of AJAX web applications,
  - to select and manipulate elements of web page (DOM manipulation),
  - to create nice looking effects and animations on web page,
  - to create richer user interface with tabs, menus, date pickers, drag-and-drop features etc.,
  - for image manipulation, image galleries, creating of slide shows,
  - client side validation of user's input etc.

jQuery architecture is extensible. There are many plug-ins ready for use in different scenarios. For example, if you need to create some element of user interface, there is a good chance that someone else also needed the same thing before. You just need to search plug-in directory and check if there is a widget which does exactly what you need.

Will jQuery slow down my web pages

To use jQuery, you need to add a reference to its core .js file. Currently, last version is 1.5.2., and jquery-1.5.2.min.js file, minified and gzipped has 29KB. That is definitely negligible.

In addition to this, if you use jQuery UI or plug-ins, you need to reference plug-in .js files too. If you overdo in creating of some extremely "rich" user interface with too many widgets, effects and other features, then it's possible that page could download slowly because of dozens of external .js files.

jQuery alternatives

jQuery is the most popular JavaScript library, but there are numerous and also very useful alternatives. Common trait of all libraries is that they try to make JavaScript development easier. It is important to emphasize that libraries are often specialized for different purposes, like effects, animations, working with forms, images, user interface, AJAX, DOM manipulation etc. Because they not do the same thing, it is hard to compare them.

Most known alternatives to jQuery are YUI (Yahoo User Interface) library, Prototype, script.aculo.us, MooTools, Qooxdoo, MochiKit, Midori, Dojo, Ext JS etc.

How to obtain jQuery

If you have Visual Studio 2010 installed (including Web Developer Express version), it already includes jQuery in web project templates. You can go File -> New Project -> ASP.NET Web Application or ASP.NET MVC web Application, or File -> New Web Site -> ASP.NET Web Site. In each case newly created project contains folder named /scripts where jQuery files are located.

jQuery .js files inside of Solution Explorer
Image 1: jQuery .js files inside of Visual Studio Solution Explorer

To create new web application or web site without jQuery, choose ASP.NET Empty Web Application or ASP.NET Empty Web Site.

Of course, you can also add these .js files manually. Newest version and all previous versions of jQuery library could be downloaded from http://docs.jquery.com/Downloading_jQuery#Download_jQuery.

How to include jQuery library in ASP.NET page

After you created new ASP.NET project with included jQuery 1.4.1. version, or placed newest jQuery version manually, you can use jQuery in ASP.NET page.

To add a reference to jQuery, use same syntax like for any other JavaScript .js file:

<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>

So, in this example, we look into Scripts folder where jquery-1.4.1.js file should be located. This is suggested location by Visual Studio project template. jQuery .js file could be located on other location if you want, even on other web server.

Very often, developers point to Google or Microsoft's server instead of local folder. The benefit of external reference is decreasing of bandwith costs. Also, since jQuery is extremely popular, there is significant chance that your visitor already has jQuery .js file cached on local computer. In this case, there is no need to download same .js again. On this way, using Google or Microsoft's servers speed up your page load and increases user's experience.

To load jQuery library from Google's server, you can use this syntax:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js " type="text/javascript"></script>

Also, you can use link from Microsoft Content Delivery Network (CDN):
http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.2.min.js

Hello World in jQuery

When developer learns new technology, first example is traditionally "Hello World" application. So, let see how we could create Hello World in jQuery.

Open Visual Studio and create new ASP.NET Web Application, or new ASP.NET Web Site. Open Default.aspx page and go to Source view. Paste following markup code:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <!-- Reference to core jQuery .js file. Instead of local folder, this reference could point to location on Internet -->
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

    <script language="javascript" type="text/javascript">
        // This function executes on page load event
        $(function () {
            // Button click will call the function bellow
            $("#btnSayHello").click(function () {
                // Finds div element with ID = "HelloMessage" and places
                // Hello World! text inside of it
                $("#HelloMessage").html("Hello World!");
        })
    })
    </script>
    <h2>
        First jQuery Example
    </h2>
    <p>
        Click on button to execute jQuery method!
    </p>
    <p>
        <!-- Click on this button will execute jQuery method -->
        <input id="btnSayHello" type="button" value="Click Me" />
    </p>
    <!-- Here is an empty div tag where we'll write Hello World message -->
    <div id="HelloMessage"></div>
</asp:Content>

If you start application and click on button, Hello World! message will appear inside of div tag.

Quick review of given JavaScript code shows that $ (dollar) character occurs three times. $ character is important in jQuery and this is the entrance into jQuery world.

General rule of jQuery syntax is:

$(SelectSomeObject).ChooseSomejQueryMethod(Place Some Parameters between brackets);

So, in last example we had a line:

$("#HelloMessage").html("Hello World!");

With $ character, we accessed jQuery. Then, by using "#btnSayHello" as a parameter, we selected an HTML element which has ID = "btnSayHello". On this way we select object which will be used later in syntax. Finally, after dot we used jQuery html method and placed welcome message in selected object, as one parameter. I think it is pretty simple syntax, isn't it? :)

In addition to this, some jQuery objects could contain one or more sub-objects divided by dots, but syntax stays the same. There could be many sub-objects, but all are separated by a dot, which is familiar syntax to developers in other programming languages like C# orVB.NET.

To easier developer's life, Visual Studio provides jQuery intellisense so you don't need to remember all that objects and methods. When you type $ character inside of <script> tag, you can see a list of jQuery objects with their descriptions:

jQuery Intellisense in Visual Studio
Image 2: jQuery intellisense in Visual Studio

jQuery plug-ins

jQuery core library can be extended, to provide abstraction over core functionality. jQuery UI library contains over 30 components, like Datepicker, Tabs, Slider, different effects, elements for interaction with user etc.

In addition to this, you can create your own jQuery plugin to get feature you want. jQuery community is very active and there are thousands of plugins published on http://plugins.jquery.com , which are sorted in several categories, like Ajax, Animation and Effects, Browser Tweaks, DOM, Data etc. It is good idea to look into this directory first, and possibly avoid creating of something from scratch.

jQuery With ASP.NET - Remarks

Remember that jQuery is just JavaScript. So, if some web browser doesn't support JavaScript, or user is deliberately turned off JavaScript, jQuery also will not work.

jQuery syntax is simple in general. jQuery motto "write less, do more" sounds very appealing. However, notice that "write less" doesn't mean "write fast". Although you can do a lot with single line of jQuery code, it is not always easy to write the line directly from head. jQuery objects, especially if you work with plug-ins, could have numerous parameters and for many people is difficult to remember them. So, while you work in jQuery, you will probably often have to look into documentation to see which parameters certain object requires.

There are security issues related to using of jQuery with ASP.NET. Since jQuery executes on client side it can be easily manipulated by malicious user. Any information that comes from jQuery to ASP.NET server side code, through AJAX or on any other way, should be treated as potentially dangerous user's input.

I hope that jQuery looks a little friendlier to you after reading of this article :). More about jQuery you can find on its official website, www.jquery.com.

Happy coding!


Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |   Google