There are several approaches to use AJAX callback in ASP.NET. We can use:
- PageMethods in WebForms (but not in User Controls)
- Implement ICallbackEventHandler for your code-behind class
and use later jQuery post or get methods to call webforms or pagemethods (but not methods from your own user controls).
But they all have some disadvantages or limitations, for instance:
- Using UserControl you can’t use PageMethods in the control declaration (inside markup and scripts)
- Using Script Services you are forced to spread the logic specific only to current user control throughout the web application instead of placing this logic inside your code-behind class of user control.
- ICallbackEventHandler approach is more powerfull but also is more difficult and more specific to current user control logic.
This project aims to allow developers to use server side methods in the client scripts more easily and in more convinient way without any unnecessary actions to provide serialization/deserialization of parameters or results from server side (for example,
using json), using only the same method signatures on the client side as they are declared on the server side code-behind class.
Only one agreement will be required - declared server side method has to return AjaxResponse or inherited class value. Needless to say that all parameters and return value must be serializable.
OK, let me show:
Create an user control in your web application and inherit code-behind class from AjaxAvailableUserControl. In attached sample web application (look at source code), I created DemoUserControl.ascx to show you how it should look like:
After that, you can declare some of the methods you possibly want to use on the client side. For example:
As you can see, on the client side we use $.execute jQuery plug-in to call the server side method by specifying the method name and the parameter names and their values. Usually, on the client side we use two handlers to process callbacks - onSuccess and onError mentioned above.
onSuccess handler receives an parameter named "data" - it's just a result from server side method; in our case, this is the returned value from MyDemoMethod1 method.
AjaxResponse class contains several useful fields to use in jQuery UI grids, but you always could inherit it and use your own custom implementation for your specific behavior.
OK, Where is it possible to apply?
There are many places to be convenient to use this approach, for example, in classical ASP.NET WebForms applications, where the significant part of projects is spread into user controls used to build eventually the final pages, or to build SharePoint Visual Web Parts which are based on User Controls, or to implement SiteCore Sublayouts which are also based on ASP.NET User Controls.
All comments and suggestions are welcome, many thanks for your time and attention.
Not affiliated with Microsoft and CodePlex
To remove your project or any question, please contact us: [email protected]