SlideShare a Scribd company logo
Building intranet applications
with ASP.NET AJAX and jQuery
Alek Davis
2009
09/03/15Building intranet applications with ASP.NET AJAX and jQuery2 of
43
Intro
• Speaker
– Alek Davis: Technoblog: http://alekdavis.blogspot.com
• Goals
– Basic understanding of jQuery, ASP.NET AJAX
– Know how to build an application using ASP.NET AJAX and jQuery
– Know what can go wrong and how to fix common problems
– Know where find information, support, and tools
• Presentation
– Use as a reference
– References contain active hyperlinks
– Code samples
• Audience
– Expected to understand
• JavaScript: Basic JavaScript syntax
• ASP.NET: Postback, code-behind, viewstate, data binding
09/03/15Building intranet applications with ASP.NET AJAX and jQuery3 of
43
Topics
• Technologies
– Rich Internet Applications (RIA)
– ASP.NET AJAX
– jQuery
• Pros and cons
– ASP.NET + AJAX + jQuery
– Other alternatives
• Development
– Web design
– Common patterns
– Caveats
– Tools
– Debugging
• References
09/03/15Building intranet applications with ASP.NET AJAX and jQuery4 of
43
Rich internet applications (RIA)
• Server-side
• ASP/ASP.NET (Microsoft)
• JSP (Sun)
• PHP
• Client-side
– virtual machine (plug-in) based
• Flash/Flex (Adobe)
• Java/JavaFX (Sun)
• Gears (Google)
• Silverlight (Microsoft)
• BrowserPlus (Yahoo!)
• Curl
– JavaScript based
• ASP.NET AJAX
• Yahoo! User Inter Interface (YUI) Library
• Google AJAX APIs, Data (GData) APIs, …
• jQuery, Prototype, MooTools, Dojo, script.aculo.us, …
09/03/15Building intranet applications with ASP.NET AJAX and jQuery5 of
43
Comparing RIA technologies
• Server-side
– Pros: ease of development
– Cons: user experience (flicker), server load, web traffic
• Client-side virtual machine based
– Pros: user experience, capabilities, platform support
– Cons: user experience, platform support, no HTML benefits
• Client-side JavaScript based
– Pros: user experience, availability, graceful degradation (NOSCRIPT)
– Cons: performance (less of an issue), browser specifics, JavaScript
09/03/15Building intranet applications with ASP.NET AJAX and jQuery6 of
43
Choosing RIA technologies
• Assumptions
– Building intranet, line-of-business (LOB) application
– Using Microsoft stack (Visual Studio, etc)
• Criteria
– Utilize existing knowledge (ASP.NET)
– Development ease and speed
– Code maintainability
– Application performance
• Options
– ASP.NET AJAX
– AJAX libraries
09/03/15Building intranet applications with ASP.NET AJAX and jQuery7 of
43
ASP.NET AJAX
• Quick facts
– Comes with Visual Studio 2008 (ASP.NET 3.5)
• Add-on for Visual Studio 2005
• Overview
– 3+ primary controls
• ScriptManager (required)
– Enables ASP.NET AJAX, partial page rendering, Web service calls
• UpdatePanel (optional)
– Partial page update (see also: UpdatePanel Tips and Tricks by Jeff Prosise)
• UpdateProgress (optional)
– Progress indicator
– Add-ons
• ASP.NET Control Toolkit
– Open-source project
– Last release: Aug 20, 2008; last update: Dec 17, 2008
• jQuery
09/03/15Building intranet applications with ASP.NET AJAX and jQuery8 of
43
Learning ASP.NET AJAX
• Documentation
– Adding AJAX and Client Capabilities Roadmap
• Web sites
– http://ajax.asp.net (main site)
– http://asp.net/AJAX/Documentation/Live/ (old, but good examples)
– http://encosia.com/ (ASP.NET, AJAX, and more; articles, tutorials, tips, RSS)
– http://mattberseth.com/blog/aspnet_ajax/ (articles, tips, RSS)
• Presentations/talks/demos/screencasts
– ASP.NET AJAX 100 by Bruce Kyle (16 min)
– ASP.NET AJAX Futures by Bertrand Le Roy at PDC 2008 (84 min)
– Building Great AJAX Applications from Scratch Using ASP.NET 3.5 and Visual Studio 2008 by
Brad Adams at MIX 2008 (76 min)
– Real-World AJAX with ASP.NET by Nikhil Kothari at MIX 2008 (75 min)
• Books
– ASP.NET AJAX UpdatePanel Control by Matt Gibbs, Bertrand Le Roy
– More from Amazon
09/03/15Building intranet applications with ASP.NET AJAX and jQuery9 of
43
jQuery
• Quick facts
– JavaScript library (file) created by John Resig
– Open source (MIT and GPL licenses; good for commercial use)
– Current version: 1.3 (released on January 21, 2009)
– Size: ~18 KB
– Browser support: IE 6+, Firefox 2+, Opera 9+, Safari 2+, Chrome
– Actively developed
– Large and active community
– Used by many companies (Google, IBM, Amazon, Dell, Netflix, Intel, …)
– Shipped with ASP.NET MVC Framework
– Will be included in next versions of Visual Studio
– 24/7 support by Microsoft through Product Support Services (PSS)
• See also
– Learning jQuery @ MIT (presented by John Resig at MIT)
• More facts, performance benchmarks, key features
09/03/15Building intranet applications with ASP.NET AJAX and jQuery10 of
43
Learning jQuery
• Web sites
– http://jquery.com/ (downloads, docs, tutorials, bug tracker, forums)
– http://www.learningjquery.com/ (tips, techniques, tutorials, RSS)
• Tutorials/articles
– jQuery for Absolute Beginners (15 short videos, about 5 minutes each)
– An introduction to jQuery (Part 1: The Client Side)
– Using jQuery with ASP.NET (Part 2: Making Ajax Callbacks to the Server)
• Books
– Learning jQuery: … by Karl Swedberg & Jonathan Chaffer
– jQuery Reference Guide by Karl Swedberg & Jonathan Chaffer
– jQuery in Action by Bear Bibeault & Yehuda Katz
09/03/15Building intranet applications with ASP.NET AJAX and jQuery11 of
43
jQuery basics
• Syntax
– $('select element').doSomething('info').doSomethingElse('more info');
• Selectors
– $('#txtSearchBox'): element with ID txtSearchBox
– $('.SelectedCell'): element(s) with class attribute SelectedCell
– $('#userGrid tr:even'): even rows of the element with ID userGrid
– $('input:checkbox[id$='chkDelete']'): input element(s) of the type
checkbox with ID that ends with chkDelete
– $('img.ImgLink[id$='imgOK'],img.ImgLink[id$='imgCancel']'): IMG
element(s) with class attribute ImgLink and ID ending with imgOK or
imgCancel
• Animations
– $(…).hide() $(…).show()
– $(…).fadeIn("fast") $(…).fadeOut("slow")
– $(…).slideUp(1000) $(…).slideDown(5000)
– …
09/03/15Building intranet applications with ASP.NET AJAX and jQuery12 of
43
More jQuery
• Common operations
– $(…).preventDefaults(): prevents default behavior
– $(…).attr(): sets/gets attribute value
– $(…).css(): sets/gets CSS attribute value
– $(…).val(): sets/gets value of a text input element (text box, text area)
– $(…).text(): sets/gets text value of an element (span, etc)
– …
• Events
– $(…).click(function(e){ … }): on click event handler
– $(…).keydown(function(e){ … }): on key down event handler
– $(…).hover(function(){ … }, function()): on hover (in and out) event handler
– $(…).bind("eventX eventY …", …): binds one or more event to event hander
– …
09/03/15Building intranet applications with ASP.NET AJAX and jQuery13 of
43
jQuery extras
• jQuery UI
– jQuery widgets
• Handle drag-and-drop, sorting, resizing, selecting
• Accordion, date picker, dialog, progress bar, slider, tabs controls
• Effects (color animation, class transitions, theming)
• Plugins
– Third party widgets
• User interface
• Data manipulation
• AJAX
• …
– See also: Plugins/Authoring
• See also
– http://docs.jquery.com/ (documentation)
09/03/15Building intranet applications with ASP.NET AJAX and jQuery14 of
43
jQuery demo
• Features
– Custom search box
• Auto-show, auto-hide
• Submit, cancel
• Buttons and keyboard
• Input validation
09/03/15Building intranet applications with ASP.NET AJAX and jQuery15 of
43
ASP.NET AJAX + jQuery benefits
• Why ASP.NET?
– Server-side (code-behind) programming
• Why ASP.NET AJAX?
– Simple partial page updates and progress indicator
– Simple asynchronous postbacks and partial page updates
– Can reuse code-behind (no additional code for Web services)
– Graceful degradation (<NOSCRIPT>)
– Less JavaScript code
• Why jQuery?
– Efficient, small, clean JavaScript; shields from browser specifics
– Complements ASP.NET AJAX: offers animations, selectors, plugins
– Minor overlap with ASP.NET AJAX (unlike other JavaScript libraries)
• Why ASP.NET AJAX (UpdatePanel, UpdateProgress) + jQuery?
– Less code (clean code)
– Reasonable efficiency (not the best, but good enough)
09/03/15Building intranet applications with ASP.NET AJAX and jQuery16 of
43
ASP.NET AJAX + jQuery limitations
• Why not use ASP.NET AJAX (UpdatePanel, UpdateProgress) +
jQuery?
– Performance (in certain scenarios)
– HTML payload
– ViewState size
– Not pure
• Alternatives
– ASP.NET AJAX + DHTML
– ASP.NET (without AJAX) + jQuery
– ASP.NET AJAX (without UpdatePanel) + jQuery
– ASP.NET AJAX + ASP.NET AJAX Toolkit + jQuery (just kidding)
• Video (good talk describing one alternative)
– ASP.NET and jQuery by Stephen Walther at PDC 2008 (74 min)
09/03/15Building intranet applications with ASP.NET AJAX and jQuery17 of
43
Web development
• Design skills
– Don't Make Me Think by Steve Krug
– The Non-Designer's Design Book by Robin Williams
– SitePoint TechTimes and SitePoint Design View newsletters
• Graphics (*free* icons)
– Visual Studio 2008 Image Library
– Sweetie icons (2 collections: BasePack and WebCommunication)
– ICONlook: the icon search
– Crystal Project (see also Crystal Clear)
– See also: 14 Free Icon Resources
• CSS frameworks
– BlueprintCSS
– YUI Grid CSS
– See also: List of CSS frameworks
09/03/15Building intranet applications with ASP.NET AJAX and jQuery18 of
43
Browsers and tools
• Firefox
– Use IE Tab add-on to switch between Firefox and IE views
– Use Web Developer add-on/toolbar for… lots of things
– Use Firebug add-on for debugging
• console.log is your friend
– Use YSlow add-on to see performance score
– More add-ons
• iMacros creates macros for task automation
• FireRainbow enables JavaScript syntax highlighting for Firebug
• Internet Explorer
– Use Fiddler to debug HTTP traffic
– Use Internet Explorer Developer Toolbar for debugging
– Use IE7Pro add-on for "everything" else
• Web tools
– jQuery API Browser
– Visual jQuery
09/03/15Building intranet applications with ASP.NET AJAX and jQuery19 of
43
ASP.NET AJAX + jQuery demo
• Features
– ASP.NET AJAX (.NET 3.5) + jQuery 1.3
– Repeater control
• Each item in Repeater is an UpdatePanel
• Each UpdatePanel holds an UpdateProgress control
– jQuery is responsible for DHTML operations
09/03/15Building intranet applications with ASP.NET AJAX and jQuery20 of
43
Application settings and configuration
• Enable a Visual Studio project for ASP.NET AJAX
– Set Target Framework (in the project Properties – Application tab)
to .NET Framework 3.5
– For upgraded projects (e.g. migrated from VS 2005 to VS 2008)
• Don't use <xhtmlConformance mode="Legacy"/> in Web.config; otherwise,
you may get the following error:
"'Sys.WebForms.PageRequestManager' is null or not an object"
– See Scott Guthrie's post (read comments on suggestions for customization of the
xhtmConformance settings)
09/03/15Building intranet applications with ASP.NET AJAX and jQuery21 of
43
Adding ASP.NET AJAX functionality
• Use ScriptManager control
– Set EnablePartialRendering attribute to true
<asp:ScriptManager
id="ScriptManager1"
EnablePartialRendering="true"
runat="server">
…
</asp:ScriptManager>
– Include references to JavaScript files in the <Scripts> section
09/03/15Building intranet applications with ASP.NET AJAX and jQuery22 of
43
Using jQuery in a project
• Options
– Option 1: Reference distribution source (Google)
• Pros: Download speed, caching, proximity
• Cons: External reference
– Option 2: Make your own copy
• Pros: Internal reference
• Cons: Download speed (possibly)
• Example
<asp:ScriptManager …>
<Scripts>
<asp:ScriptReference Path="~/Scripts/jQuery-1.3.1-vsdoc.js" />
</Scripts>
</asp:ScriptManager>
09/03/15Building intranet applications with ASP.NET AJAX and jQuery23 of
43
jQuery and IntelliSense
• The documentation (-vsdoc.js) file
– Use for documentation only (the official file at Google is buggy)
– If official version is not available (e.g. immediately after release)
• Generate vsdoc file via InfoBasis JQuery IntelliSense Header Generator
– Generated stub file contains no code (only comments)
• Usage options
– If using VS 2008 SP1
• Install hotfix KB958502 (see Visual Studio patched for better jQuery IntelliSense)
• Add the vsdoc file to the project; do not reference it in code
• Vsdoc file must have the same name as the original with –vsdoc suffix
– If not using VS 2008 SP1 (also see the Resources slide)
• Add the vsdoc file to the project
• Wrap the vsdoc file in an invisible control (use appropriate name):
<asp:Label Visible="false" runat="server">
<script src="../Scripts/jQuery-1.3.1-vsdoc.js" type="text/javascript" />
</asp:Label>
• In JavaScript files, add at the top (use appropriate name):
/// <reference path="jQuery-1.3.1-vsdoc.js"/>
09/03/15Building intranet applications with ASP.NET AJAX and jQuery24 of
43
jQuery code
• Traditional jQuery code
– Does not work after partial postback
$(document).ready(function() // or $(function()
{
// JavaScript code here
// …
});
• ASP.NET AJAX-specific jQuery
– Works after partial postback
//$(function()
function pageLoad(sender, args)
{
// JavaScript code here
// …
}
//});
09/03/15Building intranet applications with ASP.NET AJAX and jQuery25 of
43
UpdateProgress control
• Basics
– Works with UpdatePanel control
– Invisible during initial page load and full postback
– Visible only during partial postback
– Can implement UpdateProgress as a user control
• Advanced
– Modal UpdateProgress for UpdatePanel – Revisited by Damien White
• *Free* progress indicators (graphics)
– Activity indicators
– Ajaxload: Ajax loading gif generator
09/03/15Building intranet applications with ASP.NET AJAX and jQuery26 of
43
Anatomy of a postback
• Full postback
– Client  server: GET (initial request, URL)
– Server  client: <HTML>…<BODY></BODY></HTML>
– Client  server: POST (form data, including VIEWSTATE)
– Server  client: <HTML>…<BODY></BODY></HTML>
• Partial postback
– Client  server: GET (initial request, URL)
– Server  client: <HTML>…<BODY></BODY></HTML>
– Client  server: POST (form data, including VIEWSTATE)
– Server  client: <DIV id="UpdatePanelID"></DIV>, VIEWSTATE
09/03/15Building intranet applications with ASP.NET AJAX and jQuery27 of
43
UpdatePanel control
• Basics
– Embeds contents in the <DIV></DIV> tags
– Set UpdateMode attribute to Conditional
– Not everything can be implemented as an UpdatePanel
• Cannot include <TR> elements in UpdatePanel
• Using UpdatePanel with data-bound controls
– Using Eval (slower)
<asp:ImageButton … CommandArgument='<%# DataBinder.Eval("ID") %>'/>
– Using DataBinder.GetPropertyValue (faster)
<a …><%# DataBinder.GetPropertyValue(Container.DataItem, "Name") %></a>
– For complex formatting use String.Format
<asp:HyperLink …
NavigateUrl='<%# String.Format("?ID={0}&Mode={1}", Eval("ID"), Eval("Mode"))
%>' />
• Accessing controls in UpdatePanel
09/03/15Building intranet applications with ASP.NET AJAX and jQuery28 of
43
How to find a control?
• Helper function
– Find control recursively
public static Control FindControl(Control start, string id) {
Control foundControl;
if (start != null) {
foundControl = start.FindControl(id);
if (foundControl != null) return foundControl;
foreach (Control c in start.Controls) {
foundControl = FindControl(c, id);
if (foundControl != null) return foundControl;
}
}
return null;
}
• See also
Generic Recursive Find Control Extension by Brendan Enrick
ASP.NET 2.0 MasterPages and FindControl() by Rick Strahl
09/03/15Building intranet applications with ASP.NET AJAX and jQuery29 of
43
Accessing UpdatePanel from code-behind
• Access UpdatePanel control
private void someCtrl_Click(object sender, EventArgs e)
{
…
UpdatePanel updPanel = FindControl((Control)sender, "updPanel") as UpdatePanel;
…
}
• Access controls hosted by UpdatePanel
HtmlTable tbl = Helper.FindControl(updPanel, "tblDetails") as HtmlTable;
LinkButton lnk = Helper.FindControl(updPanel, "lnkItem") as LinkButton;
ImageButton img = Helper.FindControl(updPanel, "imgDetails") as ImageButton;
09/03/15Building intranet applications with ASP.NET AJAX and jQuery30 of
43
Find controls via jQuery
• If you do not know IDs of elements (e.g. in Repeater)
– Example: Make sure that check box A gets checked and disabled when
user checks box B (both check boxes belong to a repeater item and have
IDs chkA and chkB)
$('input:checkbox[id$='chkB']').click(function(e)
{
var elemID = $(e.target).attr('id');
var prefixID = elemID.replace(/chkB$/i, "");
var elemIDchkA = "#" + elemID.replace(/chkB$/, "chkA");
if (this.checked)
{
$(elemIDchkA).attr('checked', 'true');
$(elemIDchkA).attr('disabled', 'true');
}
else
$(elemIDchkA).removeAttr('disabled');
});
09/03/15Building intranet applications with ASP.NET AJAX and jQuery31 of
43
What is $(this)?
• this can have different contexts
– Most common contexts
• Context #1: JavaScript DOM element
– Inside of a callback function (click, hover, …)
• Context #2: jQuery object
– Inside of custom jQuery function
• Context #3: JavaScript object
– Such as an array element
• What about $(this)?
– $(this) converts a DOM object into a jQuery object
• To convert a jQuery object to a DOM object use:
– $(…).get(0) or $(…)[0]
• See also
– What is this? By Mike Alsup
– jQuery's this: demystified by Remy Sharp
09/03/15Building intranet applications with ASP.NET AJAX and jQuery32 of
43
Partial postback
• Detecting partial postback
– In code-behind
if (ScriptManager1.IsInAsyncPostBack)
{
…
}
– In JavaScript
function pageLoad(sender, args)
{
if (args.get_isPartialLoad())
{
…
}
}
09/03/15Building intranet applications with ASP.NET AJAX and jQuery33 of
43
Handle concurrent partial postbacks
• Default behavior
– Cancels running postback and switch to the new postback (confusing)
• Custom behavior
– Options: show error message, …
• How
Sys.Application.add_load(ApplicationLoadHandler);
function ApplicationLoadHandler(sender, args) {
if (!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack())
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(InitializeRequest);
}
function InitializeRequest(sender, args) {
if (Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {
args.set_cancel(true);
alert('Please wait until the already running operation finishes processing and retry.');
}
}
Sys.Application.notifyScriptLoaded();
• Example
Giving Precedence to a Specific Asynchronous Postback
09/03/15Building intranet applications with ASP.NET AJAX and jQuery34 of
43
Customize postbacks
• Default behavior
– Children of UpdatePanel automatically invoke (partial) postback
• Unless AutoPostBack property is set to false
• Custom behavior
– Can specify which controls/events perform partial/full updates
• Use <Triggers> section of UpdatePanel control
<asp:UpdatePanel … UpdateMode="Conditional">
<Triggers>
<asp:PostBackTrigger ControlID="btnFull" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnPartial" EventName="Click" />
</Triggers>
<ContentTemplate>
…
</ContentTemplate>
</asp:UpdatePanel>
• See also
– Understanding ASP.NET AJAX UpdatePanel Triggers
09/03/15Building intranet applications with ASP.NET AJAX and jQuery35 of
43
Handle errors from partial postback
• Default behavior
– Does not display errors (non-documented change in ASP.NET 3.5)
• Custom behavior
– Show error message box, or show inline error message, or …
• How
– Add OnAsyncPostbackError attribute to ScriptManager element
<asp:ScriptManager … OnAsyncPostbackError="ScriptManager1_AsyncPostBackError">
– In OnAsyncPostbackError event handler, set AsyncPostBackErrorMessage
property of the ScriptManager object (see next slide)
ScriptManager1.AsyncPostBackErrorMessage = e.Exception.Message;
– Add JavaScript code to handle error event and process error message
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequest);
function EndRequest(sender, args){/* see next slide */}
• Examples
– Handling Errors During a Partial-page Postback by Matthew Ellis
– How to improve ASP.NET AJAX error handling by Dave Ward (read comments)
09/03/15Building intranet applications with ASP.NET AJAX and jQuery36 of
43
Error handlers
• Server-side (code-behind)
protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e) {
if (e.Exception.Data["UserError"] == null)
ScriptManager1.AsyncPostBackErrorMessage = e.Exception.Message;
else
ScriptManager1.AsyncPostBackErrorMessage = e.Exception.Data["UserError"].ToString();
}
• Client-side (JavaScript)
function EndRequest(sender, args) {
if (!args.get_error()) return true;
if (args.get_error().message == null || args.get_error().message.length == 0)
return true;
// Get message without the prefix (name of exception type).
var msg = args.get_error().message.replace(/^[^:]+:s*/, "");
if (msg == null || msg.length == 0) return true;
alert(msg);
args.set_errorHandled(true);
}
09/03/15Building intranet applications with ASP.NET AJAX and jQuery37 of
43
Processing control info
• In ASPX code
<asp:LinkButton …
ID="lnkItem"
Text='<%# Eval("Name") %>'
OnClientClick='<%# String.Format("return ToggleDetails("{0}");",
lnkItem.ClientID) %>'
OnClick="lnkItem_Click"
CommandArgument='<%# Eval("ID") %>' />
• In JavaScript
function ToggleDetails(elemID) {
…
if (/* panel has not been initialized, pass event to server */)
return true;
// Assume that $(…) returns a details panel
if ($(…).is(':visible')) $(…).hide();
else $(…).show();
// Suppress default operation caused by click event.
return false;
}
09/03/15Building intranet applications with ASP.NET AJAX and jQuery38 of
43
Obtaining control info in code-behind
• In code-behind
private void lnkItem_Click(object sender, EventArgs e)
{
…
int id = 0;
if (sender is LinkButton)
id = Convert.ToInt32(((LinkButton)sender).CommandArgument);
else
…
…
}
09/03/15Building intranet applications with ASP.NET AJAX and jQuery39 of
43
Other ASP.NET AJAX considerations
• ViewState
– May need to disable ViewState for controls updated via JavaScript
• Invisible elements
– Be careful with <… Visible="false" />; jQuery may not find these
elements
• Use <… style="display:none;" /> if possible
– See also
• ATLAS UpdatePanel problem with Postback Scripts and invisible controls by Rick Strahl
09/03/15Building intranet applications with ASP.NET AJAX and jQuery40 of
43
Other jQuery considerations
• Text values
– Know when to use $(…).text() or $(…).val()
• Prevent default behavior
– Use e.PreventDefaults or return false from function
• Repeated click events
– Not sure why
09/03/15Building intranet applications with ASP.NET AJAX and jQuery41 of
43
What's next?
• Interesting topics
– Page methods (see ASP.NET AJAX Page Methods by Damien White)
– jQuery, UpdatePanel, UpdateProgress in master pages
– jQuery, UpdatePanel, UpdateProgress in user controls
– Calling Web services via client-side proxy classes in ASP.NET AJAX
– Using client templates in ASP.NET 4.0 AJAX
– Using jQuery plugins
– Writing jQuery plugins
– Using jQuery UI
09/03/15Building intranet applications with ASP.NET AJAX and jQuery42 of
43
Videos
• Presentations/talks/demos/videocasts/samples
– Performance Improvements in Browsers by John Resig at Google (92 min)
– MIX08 Presentation : Real-World AJAX with ASP.NET Video by Nikhil Kothari (references to
presentations/demos/talks/samples)
– ASP.NET 3.5: Adding AJAX Functionality to an Existing ASP.NET Page by Todd Miranda
– ASP.NET Podcast Show #128 - AJAX with jQuery by Wallace B. (Wally) McClure
09/03/15Building intranet applications with ASP.NET AJAX and jQuery43 of
43
Resources
• JavaScript
– Create Advanced Web Applications With Object-Oriented Techniques by Ray Djajadinata
• jQuery
– The Grubbsian: jQuery (a few interesting articles)
– jQuery for JavaScript programmers by Simon Willison
• jQuery, ASP.NET, AJAX
– Tales from the Evil Empire by Bertrand Le Roy
– Blog - Microsoft .NET, ASP.NET, AJAX and more by Visoft, Inc.
• IntelliSense
– JQuery 1.3 and Visual Studio 2008 IntelliSense by James Hart
– (Better) JQuery IntelliSense in VS2008 by Brad Vin
– JScript IntelliSense FAQ
• Rich Internet Applications (RIA)
– Developing rich Internet applications (RIA) by Alek Davis (links to many samples)
• CSS
– Which CSS Grid Framework Should You Use for Web Design?

More Related Content

PPT
Building intranet applications with ASP.NET AJAX and jQuery
PPTX
Vlad Zelinschi - Embrace Native JavaScript (the anti-plugins talk) - Codecamp...
PPTX
jQuery - the world's most popular java script library comes to XPages
PDF
Angular mobile angular_u
PDF
Backbone JS for mobile apps
PDF
Web without framework
PPTX
Getting started with rails active storage wae
PDF
Fast mobile web apps
Building intranet applications with ASP.NET AJAX and jQuery
Vlad Zelinschi - Embrace Native JavaScript (the anti-plugins talk) - Codecamp...
jQuery - the world's most popular java script library comes to XPages
Angular mobile angular_u
Backbone JS for mobile apps
Web without framework
Getting started with rails active storage wae
Fast mobile web apps

What's hot (20)

PPTX
RapidApp - YAPC::NA 2014
PPTX
Rapi::Blog talk - TPC 2017
PDF
Develop realtime web with Scala and Xitrum
PPTX
2011 NetUG HH: ASP.NET MVC & HTML 5
PDF
An Intense Overview of the React Ecosystem
PPTX
Developing Complex WordPress Sites without Fear of Failure (with MVC)
PDF
How to write a web framework
PPTX
ASP.NET MVC and Entity Framework 4
PPTX
Yui conf nov8-2010-introtoyql
PPTX
MVC and Entity Framework 4
KEY
Flash And Dom
PPTX
2012 - HTML5, CSS3 and jQuery with SharePoint 2010
PPTX
Html5 with SharePoint 2010
PDF
JavaScript Libraries (Ajax Exp 2006)
PDF
Handlebars & Require JS
PPTX
Web Ninja
PDF
Building Angular Component Libraries
PPTX
React.js at Cortex
PDF
Angular - Chapter 6 - Firebase Integration
PPTX
SeaJUG 5 15-2018
RapidApp - YAPC::NA 2014
Rapi::Blog talk - TPC 2017
Develop realtime web with Scala and Xitrum
2011 NetUG HH: ASP.NET MVC & HTML 5
An Intense Overview of the React Ecosystem
Developing Complex WordPress Sites without Fear of Failure (with MVC)
How to write a web framework
ASP.NET MVC and Entity Framework 4
Yui conf nov8-2010-introtoyql
MVC and Entity Framework 4
Flash And Dom
2012 - HTML5, CSS3 and jQuery with SharePoint 2010
Html5 with SharePoint 2010
JavaScript Libraries (Ajax Exp 2006)
Handlebars & Require JS
Web Ninja
Building Angular Component Libraries
React.js at Cortex
Angular - Chapter 6 - Firebase Integration
SeaJUG 5 15-2018
Ad

Viewers also liked (19)

DOC
PDF
The Creative Economy
PDF
Comprehensive Care Treatment Plan Presentation, Part II | Dr. Alfred Khallouf
PPTX
Syd Uni professional learning
PPT
Blogging and podcasting
DOC
Updated CV 012116
PDF
React - The JavaScript Library for User Interfaces
PPTX
How it works under the hood with visual cobol
PPT
Creative Economy
PPTX
Visual COBOL Development for Unix and Java
DOC
Menú Comedor Escolar
PDF
Treatment 1 Naomi
PPTX
BIOETHICS INVOLVED IN CLONING
PPTX
Medtech (bmls) laws &amp; bioethics intro
PDF
Lip Reconstruction Following Traumatic Lip Injuries | Dr. Alfred Khallouf
PDF
'Documents.tips panduan penulisan-laporan-akhir-ptss.pdf'
PPTX
La ciudad un escenario para el desarrollo de com petencias cientificas y ciud...
PPTX
Presentation pfe application de pointage ASP.NET
The Creative Economy
Comprehensive Care Treatment Plan Presentation, Part II | Dr. Alfred Khallouf
Syd Uni professional learning
Blogging and podcasting
Updated CV 012116
React - The JavaScript Library for User Interfaces
How it works under the hood with visual cobol
Creative Economy
Visual COBOL Development for Unix and Java
Menú Comedor Escolar
Treatment 1 Naomi
BIOETHICS INVOLVED IN CLONING
Medtech (bmls) laws &amp; bioethics intro
Lip Reconstruction Following Traumatic Lip Injuries | Dr. Alfred Khallouf
'Documents.tips panduan penulisan-laporan-akhir-ptss.pdf'
La ciudad un escenario para el desarrollo de com petencias cientificas y ciud...
Presentation pfe application de pointage ASP.NET
Ad

Similar to Building intranet applications with ASP.NET AJAX and jQuery (20)

PPT
ASP.NET AJAX with Visual Studio 2008
PPTX
Microsoft UK TechDays - jQuery and ASP.NET
PPTX
Walther Ajax4
PPTX
Walther Aspnet4
PPTX
Microsoft UK TechDays - Top 10 ASP.NET 4.0 Features
PPTX
jQuery vs AJAX Control Toolkit
PPTX
Introduction to jQuery
PPT
Daniel Egan Msdn Tech Days Oc
PPTX
PPTX
Creating Dynamic Web Application Using ASP.Net 3 5_MVP Alezandra Buencamino N...
PPT
Asp.Net Ajax Component Development
PDF
AJAX vs. jQuery What Are The Differences.pdf
PPT
ASP.NET, AJAX and jQuery
PPT
SynapseIndia asp.net2.0 ajax Development
PPT
Synapseindia dot net development web applications with ajax
PPT
Advantages and disadvantages of an ajax based client application
PPT
Techniques For A Modern Web UI (With Notes)
PPT
Ajaxppt
PPTX
New microsoft office power point presentation
PDF
What's this jQuery? Where it came from, and how it will drive innovation
ASP.NET AJAX with Visual Studio 2008
Microsoft UK TechDays - jQuery and ASP.NET
Walther Ajax4
Walther Aspnet4
Microsoft UK TechDays - Top 10 ASP.NET 4.0 Features
jQuery vs AJAX Control Toolkit
Introduction to jQuery
Daniel Egan Msdn Tech Days Oc
Creating Dynamic Web Application Using ASP.Net 3 5_MVP Alezandra Buencamino N...
Asp.Net Ajax Component Development
AJAX vs. jQuery What Are The Differences.pdf
ASP.NET, AJAX and jQuery
SynapseIndia asp.net2.0 ajax Development
Synapseindia dot net development web applications with ajax
Advantages and disadvantages of an ajax based client application
Techniques For A Modern Web UI (With Notes)
Ajaxppt
New microsoft office power point presentation
What's this jQuery? Where it came from, and how it will drive innovation

Recently uploaded (20)

PPTX
Essential Infomation Tech presentation.pptx
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
AI in Product Development-omnex systems
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
ai tools demonstartion for schools and inter college
PDF
System and Network Administration Chapter 2
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Understanding Forklifts - TECH EHS Solution
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
System and Network Administraation Chapter 3
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
Essential Infomation Tech presentation.pptx
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
AI in Product Development-omnex systems
Which alternative to Crystal Reports is best for small or large businesses.pdf
ai tools demonstartion for schools and inter college
System and Network Administration Chapter 2
Softaken Excel to vCard Converter Software.pdf
CHAPTER 2 - PM Management and IT Context
How Creative Agencies Leverage Project Management Software.pdf
Understanding Forklifts - TECH EHS Solution
Wondershare Filmora 15 Crack With Activation Key [2025
Upgrade and Innovation Strategies for SAP ERP Customers
System and Network Administraation Chapter 3
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PTS Company Brochure 2025 (1).pdf.......
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
How to Migrate SBCGlobal Email to Yahoo Easily

Building intranet applications with ASP.NET AJAX and jQuery

  • 1. Building intranet applications with ASP.NET AJAX and jQuery Alek Davis 2009
  • 2. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery2 of 43 Intro • Speaker – Alek Davis: Technoblog: http://alekdavis.blogspot.com • Goals – Basic understanding of jQuery, ASP.NET AJAX – Know how to build an application using ASP.NET AJAX and jQuery – Know what can go wrong and how to fix common problems – Know where find information, support, and tools • Presentation – Use as a reference – References contain active hyperlinks – Code samples • Audience – Expected to understand • JavaScript: Basic JavaScript syntax • ASP.NET: Postback, code-behind, viewstate, data binding
  • 3. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery3 of 43 Topics • Technologies – Rich Internet Applications (RIA) – ASP.NET AJAX – jQuery • Pros and cons – ASP.NET + AJAX + jQuery – Other alternatives • Development – Web design – Common patterns – Caveats – Tools – Debugging • References
  • 4. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery4 of 43 Rich internet applications (RIA) • Server-side • ASP/ASP.NET (Microsoft) • JSP (Sun) • PHP • Client-side – virtual machine (plug-in) based • Flash/Flex (Adobe) • Java/JavaFX (Sun) • Gears (Google) • Silverlight (Microsoft) • BrowserPlus (Yahoo!) • Curl – JavaScript based • ASP.NET AJAX • Yahoo! User Inter Interface (YUI) Library • Google AJAX APIs, Data (GData) APIs, … • jQuery, Prototype, MooTools, Dojo, script.aculo.us, …
  • 5. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery5 of 43 Comparing RIA technologies • Server-side – Pros: ease of development – Cons: user experience (flicker), server load, web traffic • Client-side virtual machine based – Pros: user experience, capabilities, platform support – Cons: user experience, platform support, no HTML benefits • Client-side JavaScript based – Pros: user experience, availability, graceful degradation (NOSCRIPT) – Cons: performance (less of an issue), browser specifics, JavaScript
  • 6. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery6 of 43 Choosing RIA technologies • Assumptions – Building intranet, line-of-business (LOB) application – Using Microsoft stack (Visual Studio, etc) • Criteria – Utilize existing knowledge (ASP.NET) – Development ease and speed – Code maintainability – Application performance • Options – ASP.NET AJAX – AJAX libraries
  • 7. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery7 of 43 ASP.NET AJAX • Quick facts – Comes with Visual Studio 2008 (ASP.NET 3.5) • Add-on for Visual Studio 2005 • Overview – 3+ primary controls • ScriptManager (required) – Enables ASP.NET AJAX, partial page rendering, Web service calls • UpdatePanel (optional) – Partial page update (see also: UpdatePanel Tips and Tricks by Jeff Prosise) • UpdateProgress (optional) – Progress indicator – Add-ons • ASP.NET Control Toolkit – Open-source project – Last release: Aug 20, 2008; last update: Dec 17, 2008 • jQuery
  • 8. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery8 of 43 Learning ASP.NET AJAX • Documentation – Adding AJAX and Client Capabilities Roadmap • Web sites – http://ajax.asp.net (main site) – http://asp.net/AJAX/Documentation/Live/ (old, but good examples) – http://encosia.com/ (ASP.NET, AJAX, and more; articles, tutorials, tips, RSS) – http://mattberseth.com/blog/aspnet_ajax/ (articles, tips, RSS) • Presentations/talks/demos/screencasts – ASP.NET AJAX 100 by Bruce Kyle (16 min) – ASP.NET AJAX Futures by Bertrand Le Roy at PDC 2008 (84 min) – Building Great AJAX Applications from Scratch Using ASP.NET 3.5 and Visual Studio 2008 by Brad Adams at MIX 2008 (76 min) – Real-World AJAX with ASP.NET by Nikhil Kothari at MIX 2008 (75 min) • Books – ASP.NET AJAX UpdatePanel Control by Matt Gibbs, Bertrand Le Roy – More from Amazon
  • 9. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery9 of 43 jQuery • Quick facts – JavaScript library (file) created by John Resig – Open source (MIT and GPL licenses; good for commercial use) – Current version: 1.3 (released on January 21, 2009) – Size: ~18 KB – Browser support: IE 6+, Firefox 2+, Opera 9+, Safari 2+, Chrome – Actively developed – Large and active community – Used by many companies (Google, IBM, Amazon, Dell, Netflix, Intel, …) – Shipped with ASP.NET MVC Framework – Will be included in next versions of Visual Studio – 24/7 support by Microsoft through Product Support Services (PSS) • See also – Learning jQuery @ MIT (presented by John Resig at MIT) • More facts, performance benchmarks, key features
  • 10. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery10 of 43 Learning jQuery • Web sites – http://jquery.com/ (downloads, docs, tutorials, bug tracker, forums) – http://www.learningjquery.com/ (tips, techniques, tutorials, RSS) • Tutorials/articles – jQuery for Absolute Beginners (15 short videos, about 5 minutes each) – An introduction to jQuery (Part 1: The Client Side) – Using jQuery with ASP.NET (Part 2: Making Ajax Callbacks to the Server) • Books – Learning jQuery: … by Karl Swedberg & Jonathan Chaffer – jQuery Reference Guide by Karl Swedberg & Jonathan Chaffer – jQuery in Action by Bear Bibeault & Yehuda Katz
  • 11. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery11 of 43 jQuery basics • Syntax – $('select element').doSomething('info').doSomethingElse('more info'); • Selectors – $('#txtSearchBox'): element with ID txtSearchBox – $('.SelectedCell'): element(s) with class attribute SelectedCell – $('#userGrid tr:even'): even rows of the element with ID userGrid – $('input:checkbox[id$='chkDelete']'): input element(s) of the type checkbox with ID that ends with chkDelete – $('img.ImgLink[id$='imgOK'],img.ImgLink[id$='imgCancel']'): IMG element(s) with class attribute ImgLink and ID ending with imgOK or imgCancel • Animations – $(…).hide() $(…).show() – $(…).fadeIn("fast") $(…).fadeOut("slow") – $(…).slideUp(1000) $(…).slideDown(5000) – …
  • 12. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery12 of 43 More jQuery • Common operations – $(…).preventDefaults(): prevents default behavior – $(…).attr(): sets/gets attribute value – $(…).css(): sets/gets CSS attribute value – $(…).val(): sets/gets value of a text input element (text box, text area) – $(…).text(): sets/gets text value of an element (span, etc) – … • Events – $(…).click(function(e){ … }): on click event handler – $(…).keydown(function(e){ … }): on key down event handler – $(…).hover(function(){ … }, function()): on hover (in and out) event handler – $(…).bind("eventX eventY …", …): binds one or more event to event hander – …
  • 13. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery13 of 43 jQuery extras • jQuery UI – jQuery widgets • Handle drag-and-drop, sorting, resizing, selecting • Accordion, date picker, dialog, progress bar, slider, tabs controls • Effects (color animation, class transitions, theming) • Plugins – Third party widgets • User interface • Data manipulation • AJAX • … – See also: Plugins/Authoring • See also – http://docs.jquery.com/ (documentation)
  • 14. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery14 of 43 jQuery demo • Features – Custom search box • Auto-show, auto-hide • Submit, cancel • Buttons and keyboard • Input validation
  • 15. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery15 of 43 ASP.NET AJAX + jQuery benefits • Why ASP.NET? – Server-side (code-behind) programming • Why ASP.NET AJAX? – Simple partial page updates and progress indicator – Simple asynchronous postbacks and partial page updates – Can reuse code-behind (no additional code for Web services) – Graceful degradation (<NOSCRIPT>) – Less JavaScript code • Why jQuery? – Efficient, small, clean JavaScript; shields from browser specifics – Complements ASP.NET AJAX: offers animations, selectors, plugins – Minor overlap with ASP.NET AJAX (unlike other JavaScript libraries) • Why ASP.NET AJAX (UpdatePanel, UpdateProgress) + jQuery? – Less code (clean code) – Reasonable efficiency (not the best, but good enough)
  • 16. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery16 of 43 ASP.NET AJAX + jQuery limitations • Why not use ASP.NET AJAX (UpdatePanel, UpdateProgress) + jQuery? – Performance (in certain scenarios) – HTML payload – ViewState size – Not pure • Alternatives – ASP.NET AJAX + DHTML – ASP.NET (without AJAX) + jQuery – ASP.NET AJAX (without UpdatePanel) + jQuery – ASP.NET AJAX + ASP.NET AJAX Toolkit + jQuery (just kidding) • Video (good talk describing one alternative) – ASP.NET and jQuery by Stephen Walther at PDC 2008 (74 min)
  • 17. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery17 of 43 Web development • Design skills – Don't Make Me Think by Steve Krug – The Non-Designer's Design Book by Robin Williams – SitePoint TechTimes and SitePoint Design View newsletters • Graphics (*free* icons) – Visual Studio 2008 Image Library – Sweetie icons (2 collections: BasePack and WebCommunication) – ICONlook: the icon search – Crystal Project (see also Crystal Clear) – See also: 14 Free Icon Resources • CSS frameworks – BlueprintCSS – YUI Grid CSS – See also: List of CSS frameworks
  • 18. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery18 of 43 Browsers and tools • Firefox – Use IE Tab add-on to switch between Firefox and IE views – Use Web Developer add-on/toolbar for… lots of things – Use Firebug add-on for debugging • console.log is your friend – Use YSlow add-on to see performance score – More add-ons • iMacros creates macros for task automation • FireRainbow enables JavaScript syntax highlighting for Firebug • Internet Explorer – Use Fiddler to debug HTTP traffic – Use Internet Explorer Developer Toolbar for debugging – Use IE7Pro add-on for "everything" else • Web tools – jQuery API Browser – Visual jQuery
  • 19. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery19 of 43 ASP.NET AJAX + jQuery demo • Features – ASP.NET AJAX (.NET 3.5) + jQuery 1.3 – Repeater control • Each item in Repeater is an UpdatePanel • Each UpdatePanel holds an UpdateProgress control – jQuery is responsible for DHTML operations
  • 20. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery20 of 43 Application settings and configuration • Enable a Visual Studio project for ASP.NET AJAX – Set Target Framework (in the project Properties – Application tab) to .NET Framework 3.5 – For upgraded projects (e.g. migrated from VS 2005 to VS 2008) • Don't use <xhtmlConformance mode="Legacy"/> in Web.config; otherwise, you may get the following error: "'Sys.WebForms.PageRequestManager' is null or not an object" – See Scott Guthrie's post (read comments on suggestions for customization of the xhtmConformance settings)
  • 21. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery21 of 43 Adding ASP.NET AJAX functionality • Use ScriptManager control – Set EnablePartialRendering attribute to true <asp:ScriptManager id="ScriptManager1" EnablePartialRendering="true" runat="server"> … </asp:ScriptManager> – Include references to JavaScript files in the <Scripts> section
  • 22. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery22 of 43 Using jQuery in a project • Options – Option 1: Reference distribution source (Google) • Pros: Download speed, caching, proximity • Cons: External reference – Option 2: Make your own copy • Pros: Internal reference • Cons: Download speed (possibly) • Example <asp:ScriptManager …> <Scripts> <asp:ScriptReference Path="~/Scripts/jQuery-1.3.1-vsdoc.js" /> </Scripts> </asp:ScriptManager>
  • 23. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery23 of 43 jQuery and IntelliSense • The documentation (-vsdoc.js) file – Use for documentation only (the official file at Google is buggy) – If official version is not available (e.g. immediately after release) • Generate vsdoc file via InfoBasis JQuery IntelliSense Header Generator – Generated stub file contains no code (only comments) • Usage options – If using VS 2008 SP1 • Install hotfix KB958502 (see Visual Studio patched for better jQuery IntelliSense) • Add the vsdoc file to the project; do not reference it in code • Vsdoc file must have the same name as the original with –vsdoc suffix – If not using VS 2008 SP1 (also see the Resources slide) • Add the vsdoc file to the project • Wrap the vsdoc file in an invisible control (use appropriate name): <asp:Label Visible="false" runat="server"> <script src="../Scripts/jQuery-1.3.1-vsdoc.js" type="text/javascript" /> </asp:Label> • In JavaScript files, add at the top (use appropriate name): /// <reference path="jQuery-1.3.1-vsdoc.js"/>
  • 24. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery24 of 43 jQuery code • Traditional jQuery code – Does not work after partial postback $(document).ready(function() // or $(function() { // JavaScript code here // … }); • ASP.NET AJAX-specific jQuery – Works after partial postback //$(function() function pageLoad(sender, args) { // JavaScript code here // … } //});
  • 25. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery25 of 43 UpdateProgress control • Basics – Works with UpdatePanel control – Invisible during initial page load and full postback – Visible only during partial postback – Can implement UpdateProgress as a user control • Advanced – Modal UpdateProgress for UpdatePanel – Revisited by Damien White • *Free* progress indicators (graphics) – Activity indicators – Ajaxload: Ajax loading gif generator
  • 26. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery26 of 43 Anatomy of a postback • Full postback – Client  server: GET (initial request, URL) – Server  client: <HTML>…<BODY></BODY></HTML> – Client  server: POST (form data, including VIEWSTATE) – Server  client: <HTML>…<BODY></BODY></HTML> • Partial postback – Client  server: GET (initial request, URL) – Server  client: <HTML>…<BODY></BODY></HTML> – Client  server: POST (form data, including VIEWSTATE) – Server  client: <DIV id="UpdatePanelID"></DIV>, VIEWSTATE
  • 27. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery27 of 43 UpdatePanel control • Basics – Embeds contents in the <DIV></DIV> tags – Set UpdateMode attribute to Conditional – Not everything can be implemented as an UpdatePanel • Cannot include <TR> elements in UpdatePanel • Using UpdatePanel with data-bound controls – Using Eval (slower) <asp:ImageButton … CommandArgument='<%# DataBinder.Eval("ID") %>'/> – Using DataBinder.GetPropertyValue (faster) <a …><%# DataBinder.GetPropertyValue(Container.DataItem, "Name") %></a> – For complex formatting use String.Format <asp:HyperLink … NavigateUrl='<%# String.Format("?ID={0}&Mode={1}", Eval("ID"), Eval("Mode")) %>' /> • Accessing controls in UpdatePanel
  • 28. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery28 of 43 How to find a control? • Helper function – Find control recursively public static Control FindControl(Control start, string id) { Control foundControl; if (start != null) { foundControl = start.FindControl(id); if (foundControl != null) return foundControl; foreach (Control c in start.Controls) { foundControl = FindControl(c, id); if (foundControl != null) return foundControl; } } return null; } • See also Generic Recursive Find Control Extension by Brendan Enrick ASP.NET 2.0 MasterPages and FindControl() by Rick Strahl
  • 29. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery29 of 43 Accessing UpdatePanel from code-behind • Access UpdatePanel control private void someCtrl_Click(object sender, EventArgs e) { … UpdatePanel updPanel = FindControl((Control)sender, "updPanel") as UpdatePanel; … } • Access controls hosted by UpdatePanel HtmlTable tbl = Helper.FindControl(updPanel, "tblDetails") as HtmlTable; LinkButton lnk = Helper.FindControl(updPanel, "lnkItem") as LinkButton; ImageButton img = Helper.FindControl(updPanel, "imgDetails") as ImageButton;
  • 30. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery30 of 43 Find controls via jQuery • If you do not know IDs of elements (e.g. in Repeater) – Example: Make sure that check box A gets checked and disabled when user checks box B (both check boxes belong to a repeater item and have IDs chkA and chkB) $('input:checkbox[id$='chkB']').click(function(e) { var elemID = $(e.target).attr('id'); var prefixID = elemID.replace(/chkB$/i, ""); var elemIDchkA = "#" + elemID.replace(/chkB$/, "chkA"); if (this.checked) { $(elemIDchkA).attr('checked', 'true'); $(elemIDchkA).attr('disabled', 'true'); } else $(elemIDchkA).removeAttr('disabled'); });
  • 31. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery31 of 43 What is $(this)? • this can have different contexts – Most common contexts • Context #1: JavaScript DOM element – Inside of a callback function (click, hover, …) • Context #2: jQuery object – Inside of custom jQuery function • Context #3: JavaScript object – Such as an array element • What about $(this)? – $(this) converts a DOM object into a jQuery object • To convert a jQuery object to a DOM object use: – $(…).get(0) or $(…)[0] • See also – What is this? By Mike Alsup – jQuery's this: demystified by Remy Sharp
  • 32. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery32 of 43 Partial postback • Detecting partial postback – In code-behind if (ScriptManager1.IsInAsyncPostBack) { … } – In JavaScript function pageLoad(sender, args) { if (args.get_isPartialLoad()) { … } }
  • 33. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery33 of 43 Handle concurrent partial postbacks • Default behavior – Cancels running postback and switch to the new postback (confusing) • Custom behavior – Options: show error message, … • How Sys.Application.add_load(ApplicationLoadHandler); function ApplicationLoadHandler(sender, args) { if (!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(InitializeRequest); } function InitializeRequest(sender, args) { if (Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) { args.set_cancel(true); alert('Please wait until the already running operation finishes processing and retry.'); } } Sys.Application.notifyScriptLoaded(); • Example Giving Precedence to a Specific Asynchronous Postback
  • 34. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery34 of 43 Customize postbacks • Default behavior – Children of UpdatePanel automatically invoke (partial) postback • Unless AutoPostBack property is set to false • Custom behavior – Can specify which controls/events perform partial/full updates • Use <Triggers> section of UpdatePanel control <asp:UpdatePanel … UpdateMode="Conditional"> <Triggers> <asp:PostBackTrigger ControlID="btnFull" EventName="Click" /> <asp:AsyncPostBackTrigger ControlID="btnPartial" EventName="Click" /> </Triggers> <ContentTemplate> … </ContentTemplate> </asp:UpdatePanel> • See also – Understanding ASP.NET AJAX UpdatePanel Triggers
  • 35. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery35 of 43 Handle errors from partial postback • Default behavior – Does not display errors (non-documented change in ASP.NET 3.5) • Custom behavior – Show error message box, or show inline error message, or … • How – Add OnAsyncPostbackError attribute to ScriptManager element <asp:ScriptManager … OnAsyncPostbackError="ScriptManager1_AsyncPostBackError"> – In OnAsyncPostbackError event handler, set AsyncPostBackErrorMessage property of the ScriptManager object (see next slide) ScriptManager1.AsyncPostBackErrorMessage = e.Exception.Message; – Add JavaScript code to handle error event and process error message Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequest); function EndRequest(sender, args){/* see next slide */} • Examples – Handling Errors During a Partial-page Postback by Matthew Ellis – How to improve ASP.NET AJAX error handling by Dave Ward (read comments)
  • 36. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery36 of 43 Error handlers • Server-side (code-behind) protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e) { if (e.Exception.Data["UserError"] == null) ScriptManager1.AsyncPostBackErrorMessage = e.Exception.Message; else ScriptManager1.AsyncPostBackErrorMessage = e.Exception.Data["UserError"].ToString(); } • Client-side (JavaScript) function EndRequest(sender, args) { if (!args.get_error()) return true; if (args.get_error().message == null || args.get_error().message.length == 0) return true; // Get message without the prefix (name of exception type). var msg = args.get_error().message.replace(/^[^:]+:s*/, ""); if (msg == null || msg.length == 0) return true; alert(msg); args.set_errorHandled(true); }
  • 37. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery37 of 43 Processing control info • In ASPX code <asp:LinkButton … ID="lnkItem" Text='<%# Eval("Name") %>' OnClientClick='<%# String.Format("return ToggleDetails("{0}");", lnkItem.ClientID) %>' OnClick="lnkItem_Click" CommandArgument='<%# Eval("ID") %>' /> • In JavaScript function ToggleDetails(elemID) { … if (/* panel has not been initialized, pass event to server */) return true; // Assume that $(…) returns a details panel if ($(…).is(':visible')) $(…).hide(); else $(…).show(); // Suppress default operation caused by click event. return false; }
  • 38. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery38 of 43 Obtaining control info in code-behind • In code-behind private void lnkItem_Click(object sender, EventArgs e) { … int id = 0; if (sender is LinkButton) id = Convert.ToInt32(((LinkButton)sender).CommandArgument); else … … }
  • 39. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery39 of 43 Other ASP.NET AJAX considerations • ViewState – May need to disable ViewState for controls updated via JavaScript • Invisible elements – Be careful with <… Visible="false" />; jQuery may not find these elements • Use <… style="display:none;" /> if possible – See also • ATLAS UpdatePanel problem with Postback Scripts and invisible controls by Rick Strahl
  • 40. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery40 of 43 Other jQuery considerations • Text values – Know when to use $(…).text() or $(…).val() • Prevent default behavior – Use e.PreventDefaults or return false from function • Repeated click events – Not sure why
  • 41. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery41 of 43 What's next? • Interesting topics – Page methods (see ASP.NET AJAX Page Methods by Damien White) – jQuery, UpdatePanel, UpdateProgress in master pages – jQuery, UpdatePanel, UpdateProgress in user controls – Calling Web services via client-side proxy classes in ASP.NET AJAX – Using client templates in ASP.NET 4.0 AJAX – Using jQuery plugins – Writing jQuery plugins – Using jQuery UI
  • 42. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery42 of 43 Videos • Presentations/talks/demos/videocasts/samples – Performance Improvements in Browsers by John Resig at Google (92 min) – MIX08 Presentation : Real-World AJAX with ASP.NET Video by Nikhil Kothari (references to presentations/demos/talks/samples) – ASP.NET 3.5: Adding AJAX Functionality to an Existing ASP.NET Page by Todd Miranda – ASP.NET Podcast Show #128 - AJAX with jQuery by Wallace B. (Wally) McClure
  • 43. 09/03/15Building intranet applications with ASP.NET AJAX and jQuery43 of 43 Resources • JavaScript – Create Advanced Web Applications With Object-Oriented Techniques by Ray Djajadinata • jQuery – The Grubbsian: jQuery (a few interesting articles) – jQuery for JavaScript programmers by Simon Willison • jQuery, ASP.NET, AJAX – Tales from the Evil Empire by Bertrand Le Roy – Blog - Microsoft .NET, ASP.NET, AJAX and more by Visoft, Inc. • IntelliSense – JQuery 1.3 and Visual Studio 2008 IntelliSense by James Hart – (Better) JQuery IntelliSense in VS2008 by Brad Vin – JScript IntelliSense FAQ • Rich Internet Applications (RIA) – Developing rich Internet applications (RIA) by Alek Davis (links to many samples) • CSS – Which CSS Grid Framework Should You Use for Web Design?