0% found this document useful (0 votes)
183 views7 pages

Ajax CheatSheet

The document summarizes key events and methods related to the Microsoft AJAX client life cycle when using ASP.NET AJAX. The Application and PageRequestManager classes raise events during page loading and processing of asynchronous postbacks that can be handled using added event handlers. Common events include load, beginRequest, endRequest, and pageLoaded.

Uploaded by

drypz
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
183 views7 pages

Ajax CheatSheet

The document summarizes key events and methods related to the Microsoft AJAX client life cycle when using ASP.NET AJAX. The Application and PageRequestManager classes raise events during page loading and processing of asynchronous postbacks that can be handled using added event handlers. Common events include load, beginRequest, endRequest, and pageLoaded.

Uploaded by

drypz
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Microsoft ASP.

NET AJAX Client Life-Cycle Events


The two main Microsoft AJAX Library classes that raise events during the client life cycle of a page are the Application and PageRequestManager classes. The key event for initial requests (GET requests) and synchronous postbacks is the load event of the Application instance. When script in a load event handler runs, all scripts and components have been loaded and are available. When partial-page rendering with UpdatePanel controls is enabled, the key client events are the events of the PageRequestManager class. These events enable you to handle many common scenarios. These include the ability to cancel postbacks, to give precedence to one postback over another, and to animate UpdatePanel controls when their content is refreshed. To add or remove handlers for events raised by the Application and PageRequestManager classes, use the add_eventname and remove_eventname methods of those classes. Note: To handle the load and unload events of the Application object, you can create functions that use the reserved names pageLoad and pageUnload.
function pageLoad() { var prm = Sys.WebForms.PageRequestManager.getInstance(); if (!prm.get_isInAsyncPostBack()) prm.add_beginRequest (onBeginRequest); }

Sys.WebForms.PageRequestManager Events
initializeRequest beginRequest Raised during initialization of an asynchronous postback. Raised before processing of an asynchronous postback starts, and the postback request is sent to the server. If there is a postback already processing, it is stopped using the abortPostBack method. Raised after a response to an asynchronous postback is received from the server, but before any content on the page is updated. Raised after all content on the page is refreshed as the result of either a synchronous or an asynchronous postback. Raised after an asynchronous postback is finished and control has been returned to the browser. If an error occurs, the page is not updated. Use this event to provide customized error notification to users or to log errors.

pageLoading pageLoaded endRequest

Sys.Application Events
init load Raised only once when the page is first rendered after all scripts have been loaded, but before objects are created. Raised after all scripts have been loaded and objects in the application have been created and initialized. Raised also for all postbacks to the server, which includes asynchronous postbacks. Raised before all objects in the client application are disposed. During this event you should free any resources that your code is holding.

unload

Based on Microsoft AJAX Library 1.0 Compiled by Milan Negovan www.AspNetResources.com Last update: 2007-08-08

Microsoft AJAX Library: String Type Extensions


String. endsWith (suffix)
Determines whether the end of a String object matches a specified string. The function is case sensitive.
var isTxt = myString.endsWith ("some_file.txt", ".txt"); // isTxt = true

var myString = "A string "; myString = myString.trim(); // myString = "A string"

String.trimStart ()
Returns a copy of the string with all white-space characters removed from the startof the string. Examples of white space characters are spaces and tabs.
var myString = " A string"; myString = myString.trim(); // myString = "A string"

String.format (format, args)


Replaces each format item in a String object with the text equivalent of a corresponding object's value.

Microsoft AJAX Library: Object Type Extensions


Object.getType (instance)
Returns the type of a specified object instance. See also Object.getTypeName ().

Remarks
args can contain a single object or an array of objects. format contains zero or

more runs of fixed text intermixed with one or more format items. At run time, each format item is replaced by the string representation of the corresponding object in the list.
var user = { FirstName: 'John', LastName : 'Doe', DOB: new Date (1975, 1, 17) }; var label = String.format ("User name: {0} {1}, born {2:d}", user.FirstName, user.LastName, user.DOB)); // label = "User name: John Doe, born 02/17/1975"

Object.getTypeName (instance)
Returns a string that identifies the run-time type name of an object. The type name is returned as a string representing the fully qualified type name.
Type.registerNamespace("Samples"); // Define and register a Samples.Rectangle class. Samples.Rectangle = function(width, height) { this._width = width; this._height = height; } Samples.Rectangle.registerClass("Samples.Rectangle"); var a = new Samples.Rectangle(200, 100); var name = Object.getTypeName(a); var type = Object.getType (a); Sys.Debug.trace ("The type name of object \"a\" is: " + name); Sys.Debug.traceDump (type); /* The result is: The type name of object "a" is: Samples.Rectangle traceDump {Function} prototype {Samples.Rectangle} __typeName: Samples.Rectangle __class: true */

String.localeFormat (format, args)


Replaces the format items in a String object with the text equivalent of a corresponding object's value. The current culture is used to format dates and numbers. See also String.format ().

String.startsWith (prefix)
Determines whether the start of a String object matches a specified string. The function is case sensitive. See also String.endsWith ().

String.trim ()
Returns a copy of the string with all white-space characters removed from the start and end of the string. Examples of white space characters are spaces and tabs.
var myString = " A string "; myString = myString.trim(); // myString = "A string"

String.trimEnd ()
Returns a copy of the string with all white-space characters removed from the end of the string. Examples of white space characters are spaces and tabs.
A function is static and is invoked without creating an instance of the object Based on Microsoft AJAX Library 1.0 Compiled by Milan Negovan www.AspNetResources.com Last update: 2007-01-24

Microsoft AJAX Library: Boolean Type Extensions


Boolean.parse (value )
Converts a string representation of a logical value to its Boolean object equivalent. The value argument must be a string representation of a Boolean value containing either "true" or "false" (case insensitive). The string can contain white space.
var b = Boolean.parse("true");

Date.parseLocale (value, formats)


Creates a date from a locale-specific string. value is a locale-specific string that can be parsed as a date, and formats (optional) is an array of custom formats. Returns an object of type Date.

Remarks
This function uses the Sys.CultureInfo.CurrentCulture property to determine the culture value.
Sys.Debug.trace (Date.parseLocale ("4/10/2001", "yyyy-MM-dd", "MM/dd/yyyy")); // Date.parseLocale will skip the first format here as invalid and use // the second one. If it does not find an appropriate format, // the function throws an exception.

Microsoft AJAX Library: Date Type Extensions


Date. format (format)
Formats a date using the invariant (culture-independent) culture.

Date.parseInvariant (value, formats)


Creates a date from a string. value is a locale-specific string that can be parsed as a date, and formats (optional) is an array of custom formats. Returns an object of type Date.
Sys.Debug.trace (Date.parseInvariant ("4/10/2001", "yyyy-MM-dd", "MM/dd/yyyy")); // Date.parseInvariant will skip the first format here as invalid and use // the second one. If it does not find an appropriate format, // the function throws an exception.

Remarks
The invariant culture is culture-insensitive. It is associated with the English language but not with any country or region. If a security decision depends on a string comparison or a case-change operation, use the Date.format method. This makes sure that the behavior will be consistent regardless of the culture settings of the system. The invariant culture must be used only by processes that require cultureindependent results, such as system services. Otherwise, the method can produce results that might be linguistically incorrect or culturally inappropriate.
var d = new Date(); Sys.Debug.trace (d.format("dddd, dd MMMM yyyy HH:mm:ss"));

Supported formats
Below are examples of supported formats to use with Date.format and Date.localeFormat (only invariant culture shown):

Format
d D t T F m (or M) s y (or Y)

Formatted date
Short date pattern (e.g.: 02/17/2007) Long date pattern (e.g: Saturday, 17 February 2007) Short time pattern (e.g.: 22:10) Long time pattern (e.g.: 22:10:30) Full date pattern (e.g.: Saturday, 17 February 2007 22:10:30) Month and day pattern (e.g.: February 17) Sortable date and time pattern (e.g.: 2007-02-17T22:10:30) Year and month pattern (e.g.: 2007 February)

Date.localeFormat (format)
Formats a date using the current culture.

Remarks
The format parameter determines how the date will be presented. The localeFormat method provides the date based on a specific culture value (locale). The culture value is also used to display web information for specific language and country combinations. This function uses the Sys.CultureInfo.CurrentCulture property to determine the culture value.
var d = new Date(); Sys.Debug.trace (d.localeFormat("dddd, dd MMMM yyyy HH:mm:ss"));

A function is static and is invoked without creating an instance of the object

Based on Microsoft AJAX Library 1.0 Compiled by Milan Negovan www.AspNetResources.com Last update: 2007-01-24

Microsoft AJAX Library: Array Type Extensions


Array.add (array, item)
Adds an element to the end of an Array object.
var a = ['a','b','c','d']; Array.add(a, 'e'); // a = ['a','b','c','d','e']

Array.forEach (array, method, context)


Performs a specified action on each element of an Array object. Skips elements in the array that have a value of undefined.
var a = ['a', 'b', 'c', 'd']; a[5] = 'e'; var result = ''; function appendToString(arrayElement, index, array) { // "this" is the context parameter, i.e. '|'. result += arrayElement + this + index + ','; } Array.forEach(a, appendToString, '|'); // result = a|0,b|1,c|2,d|3,e|4,

Array.addRange (array, items)


Copies all the elements of a specified Array object to the end of the array.
var a = ['a', 'b', 'c', 'd', 'e']; var b = ['f', 'g','h']; Array.addRange(a, b); // a = ['a','b','c','d','e','f','g','h']

Array.clear (array)
Removes all elements from an Array instance.

Array.indexOf (array, item, start)


Searches for the specified element of an Array object and returns its index. If item is not found in the array, returns -1.
var a = ['red', 'blue', 'green', 'blue']; var myFirstIndex = Array.indexOf(a, "blue"); var mySecondIndex = Array.indexOf (a, "blue", (myFirstIndex + 1)); // myFirstIndex = 1, mySecondIndex = 3

Array.clone (array)
Creates a shallow copy of an Array object.

Remarks
A shallow copy contains only the elements of the array, whether they are reference types or value types. However, it does not contain the referenced objects. The references in the new Array object point to the same objects as in the original Array object. In contrast, a deep copy of an Array object copies the elements and everything directly or indirectly referenced by the elements.
var a = ['a','b','c','d']; var b = Array.clone(a); // b = ['a','b','c','d']

Array.insert (array, index, item)


Inserts a single item into a specified index of an Array object.
var a = ['a', 'b', 'd', 'e']; Array.insert(a, 2, 'c'); // a = ['a','b','c','d','e']

Array.parse (value)
Creates an array from a string representation.
var a = Array.parse ("['red', 'blue', 'green']"); // a[0] = 'red', a[1] = 'blue', a[2] = 'green'

Array.contains (array, item)


Determines whether the specified object exists as an element in an Array object.
var a = ['red','green','blue','yellow']; var b = Array.contains(a, "red"); // b = true

Array.enqueue (array, item)


Adds the specified object to the end of an Array object. See also Array.dequeue ().

Array.dequeue (array)
Removes the first element from the Array object and returns it.
var myArray = [],result = ""; Array.add(myArray, 'a'); Array.add(myArray, 'b'); Array.add(myArray, 'c'); Array.add(myArray, 'd'); result = Array.dequeue(myArray); // myArray = ['b','c', 'd'], result = 'a'

Array.remove(array, item)
Removes the first occurrence of the specified item from an Array object.
var a = ['a', 'b', 'c', 'd', 'e']; Array.remove(a, 'c'); // a = ['a','b','d','e'] Array.removeAt(a, 2); // a = ['a','b','e']

Array.removeAt(array, index)
Removes an element from an Array object at a specified index location.
Based on Microsoft AJAX Library 1.0 Compiled by Milan Negovan www.AspNetResources.com Last update: 2007-01-24

A function is static and is invoked without creating an instance of the object

Microsoft AJAX Library: Number Type Extensions


Number.format (format)
Formats a number using the invariant culture. Use the format method to replace the Number object value with a culture-independent text representation based on the specified format parameter.

var b = new Number(2); var c = Number.parseInvariant("1.53") + a + b; // c = 7.53

Microsoft AJAX Library: Error Type Extensions


Function Error.argument Description Creates a Sys.ArgumentException object with the specified error message and the name of the invalid function parameter that caused the exception. Creates a Sys.ArgumentNullException object with the specified error message and the name of the parameter that caused this exception. Creates a Sys.ArgumentTypeException object with the specified error message and the name, actual type, and expected type of the parameter that caused this exception. Creates a Sys.ArgumentUndefinedException object with the specified error message and the name of the parameter that caused this exception. Creates a new Error object with the specified message. Creates a Sys.InvalidOperationException object with the specified error message and the name of the parameter that caused this exception Creates a Sys.NotImplementedException object with the specified error message. Creates an Sys.ArgumentOutOfRangeException object with the specified error message and the name of the argument that caused this exception Creates a Sys.ParameterCountException object with the specified error message Updates the fileName and lineNumber fields of the Error instance to indicate where the Error was thrown as opposed to where the Error was created.

Number.localeFormat (format)
Formats a number using the current culture.

Remarks
Use the localeFormat method to replace the Number object value with a text representation based on the specified format parameter. The format parameter determines how the number will be presented. The localeFormat method provides the number based on a specific culture value (locale).

Error.argumentNull

Supported formats
Below are examples of supported formats to use with Number.format and
Number.localeFormat (only invariant culture shown):

Error.argumentType

Error.argumentUndefined

Format
p d c n

Formatted number
The number is converted to a string that represents a percent (e.g.: -1,234.56 %) The number is converted to a string of decimal digits (0-9), prefixed by a minus sign if the number is negative (e.g.: -1234.56) The number is converted to a string that represents a currency amount (e.g.: (1,234.56)) The number is converted to a string of the form "-d,ddd,ddd.ddd" (e.g.: -1,234.56)
Error.create Error.invalidOperation Error.notImplemented Error.argumentOutOfRange Error.parameterCount Error.popstackFrame

Number.parseLocale (value)
Creates a number from a locale-specific string. This function uses the Sys.CultureInfo.CurrentCulture property to determine the culture value.

Number.parseInvariant (value)
Creates a floating-point numerical representation of value, if value is a valid string representation of a number; otherwise, NaN (not a number).

// Throw a standard exception type var err = Error.argumentNull("input", "A parameter was undefined."); throw err; // Throw a generic error with a message and associated errorInfo object. var errorInfoObj = { name: "SomeNamespace.SomeExceptionName", someErrorID: "436" }; var err = Error.create("A test message", errorInfoObj); throw err;

Remarks
The value argument can contain a decimal point and the "+" and "-" characters to indicate positive and negative, respectively.
var a = new Number(); a = Number.parseInvariant("4"); A function is static and is invoked without creating an instance of the object

Based on Microsoft AJAX Library 1.0 Compiled by Milan Negovan www.AspNetResources.com Last update: 2007-01-24

Microsoft AJAX Library: Sys.UI.DomElement Class


getElementById (id, element)
Gets an element with the specified id attribute. element is the parent element to search in, if specified (defaults to document otherwise).
var article = Sys.UI.DomElement.getElementById('article'); var heading = Sys.UI.DomElement.getElementById('heading', article) // Note: 'article' is an instance of Sys.UI.DomElement var btn = Sys.UI.DomElement.getElementById('<%= Submit.ClientID %>'); // Note: 'Submit' is an ASP.NET Button server control

Sets the absolute position of an element relative to the upper-left corner of its containing block. The containing block for an absolutely positioned element is the nearest ancestor with a position value other than static.

Remarks
The element is positioned via the position: absolute CSS rule. It is therefore taken out of the page flow. If there are elements that preceed and follow it, they will collapse to close the gap.
var menu = $get('menu'); Sys.UI.DomElement.setLocation(menu, 200, 50);

$get (id, element)


Provides a shortcut to the Sys.UI.DomElement.getElementById.
var article = $get('article'); var heading = $get('heading', article) // Note: 'article' is an instance of Sys.UI.DomElement var btn = $get('<%= Submit.ClientID %>'); // Note: 'Submit' is an ASP.NET Button server control

getBounds (element)
Gets the absolute coordinates of an element along with its height and width. Returns an object with the following fields:
x, y width height Absolute coordinates of an element within the browser window. See also Sys.UI.DomElement.getLocation(). Element width in pixels which includes borders, horizontal padding, vertical scrollbar (if present) and the element CSS width. Element height in pixels which includes borders, vertical padding, horizontal scrollbar (if present) and the element CSS height.

addCssClass (element, className)


Adds the specified CSS class to element.
Sys.UI.DomElement.addCssClass($get('heading'), 'highlight');

containsCssClass (element, className)


Determines if element has the specified CSS class.
var heading = $get('heading', article) var isHighlighted = Sys.UI.DomElement.containsCssClass(heading, 'highlight');

removeCssClass (element, className)


Removes the specified CSS class from element.
var heading = $get('heading', article) Sys.UI.DomElement. removeCssClass (heading, 'highlight');

var article = $get('article'); var bounds = Sys.UI.DomElement.getBounds (article); Sys.Debug.traceDump (bounds, 'Article position and size'); /* Article position and size {Sys.UI.Bounds} x: 50 y: 200 height: 268 width: 368 */

toggleCssClass (element, className)


Toggles the specified CSS class in element.
var heading = $get('heading', article) var isHighlighted = Sys.UI.DomElement.toggleCssClass(heading, 'highlight');

Note how width and height of an element include borders, padding and scrollbars. Element dimensions: 300x200 px, 20 px border, 14 px padding. "Bounds" are 368x268 px.

getLocation (element)
Gets the absolute position of an element relative to the upper-left corner of the browser window, i.e. with scrolling taken into account.
var article = $get('article'); var position = Sys.UI.DomElement.getLocation(article); var x = position.x, y = position.y;

setLocation (element, x, y)
A function is static and is invoked without creating an instance of the object Based on Microsoft AJAX Library 1.0 Compiled by Milan Negovan www.AspNetResources.com Last update: 2007-01-24

Microsoft AJAX Library: Sys.UI.DomEvent Class


addHandler (element, eventName, handler) $addHandler (element, eventName, handler
Adds a DOM event handler to an element. eventName should not include the "on" prefix.

preventDefault ()
Prevents the default event action from being raised. For example, if you prevent the hyperlink click event from being raised, the browser will not follow the link.
$addHandler ($get ("showMoreLink"), "click", showMore); function showMore (e) { e.preventDefault (); }

Remarks
In the event handler, this points to the DOM element the event was attached to, not necessarily the element that triggered the event.
Sys.UI.DomEvent.addHandler (element, "click", clickHandler); // Same as $addHandler (element, "click", clickHandler); function clickHandler (e) { }

stopPropagation ()
Prevents an event from being propagated (bubbled) to parent element(s).

Remarks
By default, event notification is bubbled from a child object to parent objects until it reaches document. Use the stopPropagation method to prevent an event from being propagated to parent elements.

addHandlers (element, events, handlerOwner) $addHandlers (element, events, handlerOwner)


Adds a list of DOM event handlers to an element. events is a dictionary of event handlers. Event names should not include the "on" prefix.
$addHandlers ($get ("article"), { mouseover: onMouseOver, mouseout: onMouseOut }); function onMouseOver (e) { this.style.backgroundColor = 'yellow'; } function onMouseOut (e) { this.style.backgroundColor = 'white'; }

Event properties
altKey button charCode clientX clientY ctrlKey offsetX offsetY Indicates if the ALT key was pressed when the event occurred. One of Sys.UI.MouseButton values: leftButton, middleButton, or rightButton. An integer value that represents the character code of the key that was pressed to raise the event. Can be one of Sys.UI.Key values: backspace, tab, enter, esc, space, pageUp, pageDown, end, home, left, up, right, down, del. The x-coordinate of the mouse pointer's position relative to the visible document area of the browser window, excluding window scroll bars. The y-coordinate of the mouse pointer's position relative to the visible document area of the browser window, excluding window scroll bars. Indicates if the CTRL key was pressed when the event occurred. The horizontal offset between the mouse position and the left side of the object that raised the event. The vertical offset between the mouse position and the top of the object that raised the event The original DOM event. The horizontal offset between the user's screen and the mouse pointer's position. The vertical offset between the user's screen and the mouse pointer's position. Indicates if the SHIFT key was pressed when the event occurred. The object that raised the event. The name of the event that was raised (e.g., "click").

Remarks
Inside each event handler, this will point to handlerOwner if it is specified (see Adding Client Behaviors to Web Server Controls Using ASP.NET AJAX Extensions in documentation). If handlerOwner is omitted, this points to the DOM element the event was attached to.

clearHandlers (element) $clearHandlers (element)


Removes all event handlers from the specified element.
Sys.UI.DomEvent.clearHandlers (element); // Same as $ clearHandlers (element);

rawEvent screenX
screenY shiftKey target type

removeHandler (element, eventName, handler) $removeHandler (element, eventName, handler)


Removes an event handler from the specified element. eventName should not include the "on" prefix.
Sys.UI.DomEvent.removeHandler (element, "click", clickHandler); // Same as $removeHandler (element, "click", clickHandler);

A function is static and is invoked without creating an instance of the object

Based on Microsoft AJAX Library 1.0 Compiled by Milan Negovan www.AspNetResources.com Last update: 2007-01-24

You might also like