download AJAX for APS.Net
I've written an AJAX library for ASP.Net applications. I got the idea from Michael Schwartz's AJAX Wrapper. It uses the same mechanism for including method signatures (inserting external .js files) but as he hasn't released the source code I'm not too sure how different/similar our implementations are but some of the known differences are:
Only uses one callback function per request (but not required, see next)
Supports synchronous calls as well as asynchronous class. If a callback function is not passed the call returns the request object.
Returns a single response object response.value (returned value/object from invoked method) response.error (exception/http error) response.request (the XmlHttpRequest)
Supports runtime checking of exposed Types - throws an exception if a method that is being exposed doesn't meet the criteria (public static method with parameters of simple types)
Using
Exposing Methods:
You can only expose public static methods with parameters of simple types such as int and bool. To expose the methods add the attribute
[Ajax.JavaScriptAccessableMethod]public static void MethodName()
Including Method wrappers:
A JavaScript wrapper is generated for each exposed method which adds an extra parameter callback at the end.
public static int TestMethod(int a, int b)
function TestMethod(a, b, callback)
as youmay have noticed JavaScript being a scripting language doesn't have the rich type system that .Net has so overloaded methods won't work.
To include a type's wrappers register the type during the loading of the the Page or UserControl.
private void Page_Load(object sender, System.EventArgs e){Ajax.MethodHelper.Register(typeof(TypeName));}
Only the methods declared in the type will be exposed so there is no security problem with exposing base class methods.
Calling method from ClientSide:
Synchronously:
function test(){var response = TypeName.MethodName(parameter1, parameter2); }
Asynchronously:
function test(){var response = TypeName.MethodName(parameter1, parameter2, callback); }function callback(response){ }
The response.error property will be null if everything went OK otherwise it will be an exception or "http" if there was a http error.
The response.value property will be the value/object of the methods return type. Objects only contain nonstatic public properties and fields.
function ajax_test_callback(response){if( !response.error ){alert('Callback value:typeof = ' + typeof(response.value) + ', value = ' + response.value);}else if( response.error == 'http' ){alert('A http error occured: ' + request.status); }else{alert('An exception occured: ' + response.error);}}