8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
1/29
ACS301:
Using jQuery with ASP.NET
Rick Strahl
West Wind Technologies
www.west-wind.com/weblog
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
2/29
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 atwww.west-wind.com/articles.asp
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
3/29
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
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
4/29
It's what the HTML DOM
should have been!
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
5/29
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!
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
6/29
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
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
7/29
Using jQuery the Basics
Add script reference to HTML:
Select elements and apply behavior:
$("#ulItemContainer>li") // select
.addClass("activelist") // apply behavior
.click(function(){}); // attach events
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
8/29
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() );
});
$("").attr("id","divNew")
.appendTo(document.body);
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
9/29
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
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
10/29
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
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
11/29
jQuery Selectors jQuery's Magic
jQuery(selector) or $(selector) Selects DOM elements
Create jQuery Object containing array ofDOM 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
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
12/29
The jQuery Wrapped Set
Contains an Array ofDom 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
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
13/29
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
14/29
jQuery and ASP.NET
Using jQuery's Ajax features
to call ASP.NET
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
15/29
Using jQuery with ASP.NET
It's plain Javascript so "it just works" No special requirements
Use as plain script include
Can also load with ScriptManager (ASP.NET Ajax)
Where to include jQuery Page
MasterPage
Load using WebResources Depends on usage scenario
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
16/29
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
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
17/29
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
DownloadjQuery Intellisense file (1.4.1)
Add jqueryvsdoc.js in same path as jquery.js
to get full Intellisense
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
18/29
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
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
19/29
Ajax Communication Models
Initialrequest: HTMLInitialrequest: HTML
HTML
Form POST
HTML + JSONHTML + JSON
JSON
JSON
Server AJAX
Pure AJAX
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
20/29
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 forData 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
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
21/29
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
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
22/29
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
23/29
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)
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
24/29
Extensibility of jQuery
Plug-ins and Building ASP.NET
controls that use and interactjQuery
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
25/29
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 ofDOM 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
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
26/29
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 fadesback into full opacity for the time interval specified.
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
27/29
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
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
28/29
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!
8/6/2019 Strahl ASP Connections IntroductionToJQuery ACS301
29/29
Resources
Download Updated Slides/Code:www.west-wind.com/files/conferences/jquery.zip
White Paperwww.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