- Server side
On the server side, we will create a normal ASMX web service.
- Right click your project in Visual Studio and click "Add new item". In the dialog that opens up, select "Web service" and give it an appropriate name
- Once the web service has been added, open it's .cs file. At the very top, before the class declaration there will be the following commented attribute
- Add the methods you want to call from the client side and annotate them with the [WebMethod] attribute
- Test the web service and ensure that the web methods are working fine
Uncomment this attribute.
- Client side
On the client side, we will need to do the following to be able to call the web service created in the above steps
- Add a ScriptManager tag at the top of your page. The script manager is required on every page that should provide AJAX functionality. It instantiates the PageRequestManager class and handles the downloading of all the necessary script and service proxy files. (If you are using master pages and the ScriptManager is present in the master page, you can add a ScriptManagerProxy tag to the current page)
- Within the ScriptManager tag, add a ServiceReference and provide the path to the web service. It should look something like this,
- The final step is to code the success and failure callbacks, syntax for which is as follows :
WebServiceClass.WebMethod(parameters, Success Callback function, Failure callback function, context);
parameters : We can specify as many as needed, or even 0, parameters to be passed to the web method, each separated from the other by comma
function SuccessCallback(response, context, method)
function FailureCallback(error, context, method)
response : It contains the values returned by the web method. It can be as simple as an integer or a string or as complex as JSON representation of List
error : Object representing the error that occurred in the web method. The most useful method of this object is get_message() which returns a description of the error that occurred
context : Optional value, which will have the same value as provided as the last parameter when calling the web method
Having the ability to call web services asynchronously from the client provides tremendous flexibility as well as performance advantages to the programmers and allows us to create really powerful and performant sites with ease.