Você está na página 1de 29

ACS301:

Using jQuery with ASP.NET


Rick Strahl West Wind Technologies www.west-wind.com/weblog

Rick Strahl Who am I?


President West Wind Technologies (Maui, Hawaii) Developer Tools Vendor Developer Training and Mentoring Web and Enterprise Development Products West Wind HTML Builder (Documentation System) West Wind Web Store (e-Commerce) West Wind Web & AJAX Toolkit Microsoft MVP C# Working with Microsoft tech for 15+ years Co-Publisher of CoDe Magazine Author Over 100+ magazine articles Large .NET article white paper archive at www.west-wind.com/articles.asp

Javascript the ugly Stepchild


Javascript's been around forever but
Minimally used for its first 10 years Few app developers were *really* proficient with Javascript Resurgence with AJAX and advent of JS libraries

Browser Incompatibilities
Varying Dom/Css implementations Varying event management interfaces Varying feature support

Javascript -> OOP mismatch


Differences between Dynamic (js) & static (C#,VB.NET) 'Different' OOP implementation

It's what the HTML DOM should have been!

Why should you consider jQuery?


jQuery provides a common Browser API
Wraps the HTML DOM in a high level API Provides browser independence (for the most part) Greatly simplifies many common tasks intuitively

Using jQuery can:


Reduce amount of Javascript code drastically Produce more robust Javascript code Produce unobtrusive Javascript

jQuery puts the fun back into Client Scripting!

What's jQuery?
Javascript HTML DOM Manipulation library Light weight (~20k compressed) Powerful and extremely practical functionality Easy to learn and intuitive to use Familiar CSS 3 based selector syntax Easy to extend through plug-in API 100's of plug-ins for just about anything Popular and getting more popular all the time

Using jQuery the Basics


Add script reference to HTML:
<script src="scripts/jquery.js" type="text/javascript"></script>

Select elements and apply behavior:


<script type="text/javascript"> $("#ulItemContainer>li") // select .addClass("activelist") // apply behavior .click(function(){}); // attach events </script>

More jQuery Examples


$("#myID").css("opacity",0.20); $(".myClass1,.myclass2").hide(); $("table>tbody>tr:even") .addClass("gridAlternate") .css( {font-weight:"bold",padding:3} ); $("#gdEntries tr").click(function(e){ alert( $(this).text() ); }); $("<div>").attr("id","divNew") .appendTo(document.body);

The Keys to jQuery


Selectors
Select DOM elements in a variety of ways CSS 3 selection syntax

jQuery Wrapped Set


Result of selector operations Array like object contains matched DOM nodes

jQuery Operational Methods


Instance methods operate on Wrapped Set Fluent interface: Most methods are chainable Browser normalization in many functions

The Keys to jQuery (continued)


Event Handling
Simple event binding functions
$("#divItem").click( function(e) {} );

Consistent event context (this = DOM element) Normalized event object to bridge browser diffs

Plug-in API
Very easy, yet powerful API jQuery.fn allows extending of Wrapped Set this context passed as Wrapped Set It's super easy! Result: 100's of plug-ins

jQuery Selectors jQuery's Magic


jQuery(selector) or $(selector)
Selects DOM elements Create jQuery Object containing array of DOM nodes Contains methods to apply against each match

Selection of elements
Id ("#id"), Class (".class"), Element ("div") DOM Instance (ctl), jQuery Instance (jCtl) [attribute],>child, descendent,+next,~siblings :first,:last,:not,:even,:odd,:contains,:parent,:empty,:hidden,:visible

http://docs.jquery.com/Selectors

The jQuery Wrapped Set


Contains an Array of Dom Nodes
$("input")[0] = first matched DOM node Check length property for matches Can use .each() to iterate over nodes

Operational functions operate on matches


DOM: .attr,.css,.addClass,.hide,.show etc. Content: .html,.text,.val,.attr Events: .click,keypress,.blur,.focus,.change Iteration: .each, Ajax: .ajax,.load,.post,.getJSON,.getScript

jQuery Utilities
'Static' methods of jQuery object
Provide generic functionality Highly useful operations Defined directly off of the static jQuery object

Highlights
$.ajax, $.post, $.getJson, $.getScript $.ready: Reliable load completion
used extensively for page setup code

$.extend: Extend one object with another


used extensively for parsing parameter maps!

$.merge: Extend an array with another $.grep: Filter arrays with function delegates

jQuery and ASP.NET

Using jQuery's Ajax features to call ASP.NET

Using jQuery with ASP.NET


It's plain Javascript so "it just works"
No special requirements Use as plain script include
<script src="scripts/jquery.js"></script>

Can also load with ScriptManager (ASP.NET Ajax)

Where to include jQuery


Page Master Page Load using WebResources Depends on usage scenario

Loading jQuery from CDN


Better performance cached Use CDN provider's bandwidth instead of your's Fallback to local if unavailable (offline dev, Google down)

One Disadvantage: No Intellisense Support

jQuery Intellisense
Visual Studio 2008 SP1 provides jQuery support
Required to get any Intellisense for jQuery and plug-ins Basic Intellisense support in the box Visual Studio 2010 has native support

Improve Intellisense Support in VS 2008


Install vsdoc.js HotFix : KB958502 Download jQuery Intellisense file (1.4.1) Add jqueryvsdoc.js in same path as jquery.js to get full Intellisense

jQuery Ajax Functionality


Easy Server Callbacks
$.ajax() is the core function with lots of options $(sel).load(): Load Html from server into DOM element $.get(),$.post(): Get raw data $.getJSON(): Get/Post and return JSON

Options
Send form data Send an object's data as querystring data Determine how data is parsed on result

Ajax Communication Models


Server AJAX
Initial request: HTML Form POST HTML

Pure AJAX
HTML + JSON JSON JSON

jQuery and Ajax (continued)


Sending Simple Data to the Server
jQuery natively prefers querystring/post data $.get(), $.post(), $.ajax() $("#form").serialize() encodes fields to POST data $.param() can encode objects to POST data Forms plug-in can auto-submit forms and callback

Using getJSON for Data Transfers


$.getJSON() one way JSON parsing from server As the name suggests only GET requests Potential security hole with array results should use POST But there's no built-in JSON Encoder Better choice: Use manual POST and convert JSON manually

JSON makes the Ajax World go 'round


JavaScript Object Notation
Lightweight object encoding format JavaScript natively decodes JSON no parsing! Encoders required for creation nothing native in jQuery Recent browsers have native JSON support Json2.js for others (same API as native)

Server Side
JavaScript Serializer (System.Web.Extensions) DataContractJsonSerializer (System.ServiceModel.Web) WCF REST Serivces ASMX ASP.NET AJAX Web Services Third Party Tools

jQuery Ajax The Server Side


JavaScript Serialization
Allows for 'manual' JSON results Javascript Serializer (System.Web.Extensions) DataContractJsonSerializer (3.5)

Server side Ajax Frameworks


ASMX Services or WCF (requires some tweaking)
MVC Framework has JSON() ActionResult

JayRock http://jayrock.berlios.de/ West Wind Web Toolkit (Page, Controls, HttpHandler)


(provided with Session Samples)

Extensibility of jQuery
Plug-ins and Building ASP.NET controls that use and interact jQuery

jQuery Plug-in Model


Easy Extensibility Model
Simple model based on function extension Extend jQuery result object or static instance

Extend jQuery Result with $.fn.yourMethod


Methods that apply against jQuery Results Methods are called in context of DOM node (this) Methods should return jQuery object for chaining

Extend static jQuery with $.yourMethod


Static methods, always available on jQuery instance Meant for generic behavior ie. all inputs are passed

A Simple Plug-in
$.fn.pulse = function(time) { if (!time) time = 2000; // this == jQuery object that contains selections this.fadeTo(time,0.30, function() { $(this).fadeTo(time,1); }); return this; // return 'this' to chain } Example: $("#ulList li:even").pulse(1500);
Applies a Pulse effect to the set of matched elements, that fades out to 30% opacity, then fades back into full opacity for the time interval specified.

Plug-In Model (continued)


Keep it simple!
Don't pollute jQuery instance Create overloaded methods Hang any instances/object of your main object

Keep it consistent
Examine existing Plug-ins Check out jquery.ui

Summary
jQuery is a powerful client side tool Easy to get started with Play with it if you haven't You'll be surprised how much easier Javascript can be with the right tool!

Resources
Download Updated Slides/Code: www.west-wind.com/files/conferences/jquery.zip White Paper www.west-wind.com/presentations/jQuery jQueryControls Documentation: http://www.west-wind.com/westwindwebtoolkit/docs jQuery Cheat Sheet http://labs.impulsestudios.ca/jquery-cheat-sheet Books:
jQuery in Action - http://tinyurl.com/2luw4e jQuery Reference Guide - http://tinyurl.com/2vhcbu Learning jQuery - http://tinyurl.com/2mzv6o

Você também pode gostar