14 Days Free Technical Video Training from WintellectNOW

  

Adding jQuery Goodness to ASP.NET Web Pages using WebMatrix

Tags: ASP.NET, ASP.NET Web Pages, jQuery, WebMatrix

Getting and using jQuery in your WebMatrix projects is a cinch, a painless way to add rich functionality with a small amount of easy to write code.  jQuery is an open source project written in JavaScript that allows developers to manipulate elements on web pages needing very little knowledge traditionally associated with writing JavaScript across multiple browsers.  For more of an overview of jQuery, see the jQuery documentation online.

Getting Started with jQuery

You have two choices for accessing/installing jQuery:

  1. Download and reference the .js JavaScript file from jQuery.com
  2. Reference the jQuery CDN (Content Delivery Network)

Either way, determining which version of jQuery to use works the same way regardless of which way you chose to obtain it. Multiple jQuery versions are stored at the CDN so all that’s needed is to update the <SCRIPT> tag on the developer’s end to point to the updated .js file.  Otherwise, you can just as easily download the updated jQuery file & modify the <SCRIPT> tag that references it. 

The next thing to do is to add the <SCRIPT> tags in the site layout file, _SiteLayout.cshtml. Since this page is incorporated into all pages in the site, all pages will have jQuery available to them.  If you know only a few pages will need jQuery, then add the <SCRIPT> tag to the bottom of those specific pages instead.

The example below references jQuery the CDN from the <script> tag.

<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.js" type="text/javascript"></script>

Now that jQuery is installed and referenced, you'll want to create your own .js file to house your own jQuery scripts.  By creating your own .js file, you can use jQuery in an unobtrusive way - meaning that HTML markup is separated from the jQuery scripts, keeping web pages and script files clean and happy.  This can be done using the built-in WebMatrix Bakery sample by creating a bakery.js file in the /Scripts folder, then referencing it with the <SCRIPT> tag in the _SiteLayout.cshtml just after the jQuery script reference. the <SCRIPT> tag will look like this.

<script src="/Scripts/bakery.js" type="text/javascript"></script>

Now you're ready to dig deeper into jQuery code to your Razor View Pages.

jQuery Ready Function

Add the jQuery ready function to the bakery.js file.  The ready function is the block of code that runs when the browser’s DOM is fully loaded, making it the perfect place to attach to events and host scripts.  Here’s what the jQuery ready function signature looks like (this is one of several different syntaxes):

$(document).ready(function() {

   

});       

We'll revisit the ready function in more depth below.  In the meantime, note that you can write any JavaScript that you'd, as you're using .js files, and jQuery itself is JavaScript, so mixing JavaScript with jQuery will work just fine.  However, I think you'll find that jQuery's syntax is much more precise and easier to work with for DOM manipulation, and JavaScript perhaps better for performing functions not related to the UI.

In writing jQuery code you must use selectors to manipulate elements using jQuery. 

jQuery Selectors

The primary objective of jQuery is to perform operations on matching sets of elements returned called a "wrapped set", which is stored under the hood as an array.   This is done in jQuery by using a syntactical expression called a selector that allows you to select & manipulate the DOM elements you want using a prescribed yet precise syntax based on CSS.  The syntax for any selector is: $(“<selector>”), where the "<selector>" could be any combination of the selectors listed in the jQuery documentation.

The following selector patterns demonstrate the varied ways to use jQuery to select DOM objects.  Note that this is not an exhaustive list by any means and there are many more selectors in the documentation online.

Selector Syntax

Description

General Selectors

$("#id")
Selects all elements that have a matching id attribute
$(".class") Selects all elements that share the same class attribute value
$("selector1, selector2, selector3...") Selects multiple disparate elements in the DOM. 

Form Selectors

$("element") Selects matching HTML elements by their tag names
$("input[attribute='value']") Selects all INPUT elements that match the specific attribute and attribute value used in the expression
$("input:not(:checked)) Selects all input elements that are not checked

Parent/Child/Navigational  Selectors

$("ul.menuitem > li") In the form of "parent.class > child", this selector returns all matching child elements to any <UL> tags that match on the menuitem class.
$("form:parent") Selects all matching parent elements of <FORM> tags.

Other Selectors

$ ("tr:even") Selects all elements with an even index
$ ("tr:odd") Selects all elements with an odd index
$ (":hidden") Selects all hidden elements

The selectors take advantage and extend the use of CSS syntax, making it really easy to grab and manipulate any combination of elements from the DOM.  If you're already familiar with CSS, you have a head start, and if you're not is continues to be necessary for quality web development.  The good news is that jQuery is structured in such a way that you'll quickly become quite good at CSS just by virtue of writing jQuery!

jQuery Methods & Events

There are no properties in jQuery, it operates solely on methods.  This is yet another reason why the syntax is precise and clear.  A jQuery method is a method on a selector using familiar dot notation to manipulate the wrapped set it returns.  To call a jQuery method, use the following syntax:

$("selector").method([arg], [arg]);

Like everything else, binding wrapped sets to events starts with the selector, then the event with code to respond to it, all inline.  You can also create functions if you'd prefer rather than put the code inline, since it's all JavaScript anyway.

$("selector").click(function() { // code to respond to event here } ) 

This example selects a wrapped set and binds it to the click event.  Using this method for binding to events means that you must know which events you can use for what type of objects.  There's a complete list of events available are in the jQuery documentation.  Using the .bind() method is another way to get the same results with DOM events not yet added to the jQuery library in the list of events. 

Getting that jQuery goodness in ASP.NET Web Pages

Now that we see how to work a bit with jQuery, we can start looking at some concrete examples.  In the code below, inside the ready() function, two things are happening:

  1. The code selects the element(s) that have their class attribute set to product-image, and calls the fadeIn() method for each of them.
  2. The code selects the element(s) that have an id attribute value of orderQty, orderTotal or orderPrice and binds each of them to their blur event. This takes an inline function as an argument, and runs that code when the event fires.  The code that runs during the blur event calculates the total price for that product.

$(document).ready(function() {

 

    $(".product-image").fadeIn("slow");  // call to fadeIn method

 

    $("#orderQty").blur(function() {

         $("#orderTotal").text(($("#orderQty").val() * $("#orderPrice").text()));

    });    // binding to the blur event of the orderQty <INPUT> element

});

Before testing out the code, the elements that have a class attribute valued at product-image class must be hidden for the fadeIn() method to work .  This is done by modifying the site's \Styles\Site.css file to add in the display style and set it's value to none.

.product-image {

    background-color: #edece8;

    ...

    display:none;           

}

Running the Bakery site in the browser will show that the all product images (that have a class of product-image) do indeed transition from transparent to opaque.  Within the order page, navigating to the the orderQty field, entering a number then navigating away works as it calculates the order total and displays it.

Once you get the hang of dealing with selectors, jQuery is lightning fast to write and is obtrusive, so it won't get mixed in with the markup.  The same sample code here could also just as easily been opened in Visual Studio for editing.  There's way more than just the jQuery core, the jQuery UI, plug-ins and lots of AJAXy awesome can be found at our CDN:  http://www.asp.net/ajaxlibrary/cdn.ashx#jQuery_Releases_on_the_CDN_0

4 Comments

  • Richard said

    Hi Rachel
    Thanks for this post. I wish understanding jQuery with MS WebMatrix for me was a cinch- sorry I am so very dumb.
    I am developing using WebMatrix as localhostserver & want jQuery setup in WebMatrix but still haven't got it doneyet. I will keep trying.
    Thanks & best wishes

  • Telsfarkamask said

    I just sent this post to a bunch of my friends as I agree with most of what you’re saying here and the way you’ve presented it is awesome.

  • James said

    Thanks Rachel,
    Not many walk-throughs out there on this topic.
    I'm new to .NET Razor, had a jquery script-- which I didn't know what to do with--and was able to get it going with this article. Thanks!

  • kapil Singh said

    This is one of the best answer so far, I have read online. No crap, just useful information. Very well presented. I had found another good collection of JQuery interview question and answer over internet.
    please check out this link...
    http://mindstick.com/Interview/368/How%20to%20add%20Jquery%20library%20in%20Asp%20net

Comments have been disabled for this content.