AJAX for Beginners (Part 3) – Calling Server Side Methods and Consuming Web Services from JavaScript in an ASP.NET website

In this article we will try to see how we can use ASP.NET AJAX framework to call the methods defined on server side i.e. code behind from client side JavaScript. We will also look at how we can invoke and use a Web Service from JavaScript. 


There are many a times in our application when we want to have some functionality on client side which is already existing on the server side. If we have some independent piece of code running on server side then there is no need to rewrite it in JavaScript on client side. We can simply use ASP.NET ajax framework to call the methods from server side.

Another benefit of using server side code is that we get all the benefits of server side language and APIs and return the result on the client side. This is sometimes very useful, given the fact that C# is way more powerful than JavaScript and .Net framework provide wider range of functionalities.

We can also use ASP.NET AJAX framework to invoke and use Web Services from JavaScript  Having the possibility of invoking and using web services from java script gives us the possibility of creating highly responsive user interface using the web services.

Note: There are few limitation when using ASP.NET AJAX framework. The server side methods that are being called from client side has to be static and none of the controls on the page can be referenced in the server side code that is being called by the client side. So having this functionality is really useful when I have an independent piece of algorithm that can be called on some input data and some output could be produced.

Using the code

All these functionalities and communication between client side and server side is taken care by ASP.NET AJAX framework. To use the ASP.NET AJAX framework, we simply need to put a ScriptManagercontrol on the page and it will take care of the rest.

To perform all the above mentioned tasks we need to write the actual server side code that contains the functionality and the JavaScript ode to call these server side code. All the boilerplate code that takes care of the communication between client and server is the ASP.NET AJAX frameworks responsibility. Let us try to understand how these can be done by looking at a sample application.

Calling a Simple Server Side Method

So the very basic possiblilty is to have a method on the server side and call it from JavaScript. Let us first define a function in our code behind file that will simply return some string message.

To make this method callable from the client side script we need to make this staticand decorate/adorn it with a WebMethodattribute.

The first thing that we need to do to be able to call the server side methods is to make the EnablePageMethods="true" in the ScriptManagercontrol.

Now lets have a button on the aspxpage that will call this method using JavaScript.

The CallServerMethodmethod is the JavaScript method that takes care of calling the server side method. the false is returned so that the default action of causing a postback is suppressed. Let us now look at the Javascript function which is actually calling the server side method.

The way to call the server side methods is to call the method defined in page using PageMethods. The argument that we need to pass to call the parameterless function is the name of the callback function that will be called to get the result. Let is look at this callback function.

Now when we run this page, the CallServerMethodwill be called. In this method we will call the server side method using PageMethodsand passing the name of the call back function OnSuccess. The return value of the server side method will come as parameter in our callback function i.e. result. Let us run the page to see the result.


Passing Values and Getting Results from Server Side Methods

Now that we are able to call a simple method from client side, let us look at how we can pass the values from client side to the server side functions. To do this let us try to write a simple calculator functionality. Let us take two inputs from the user and pass them to the server side and get back the result from server and show it to the user. In case the input is not valid the server side should send us an error and we will show the error to the user.

Now to do this first we need two input fields and a buttons to initiate the respective actions of Addition, Subtraction, Multiplication and Division.

Now each of these buttons call a server side method to initiate the respective server side function. Let us look at the implementation of Add function and other functions will be implemented on same lines.

What we are doing in this function is that we are extracting the values form the text boxes and passing it to a server side method called Add. The third parameter OnResultis the callback function which will be called when method call is successful and the fourth OnErrorwill be called when there is some error.

These callback function actually have the possibility to tell us the method from which they are being invoked i.e. the method parameter in the functions. So we can actually use the same callback function for all four functions and get the results. We will show the result with the method name to know what method is giving the result or error.

So lets implement the other three functions too.

Now we need to write the server side functions that accept 2 input parameters, calculate the result and return the result. These functions could also throw the exceptions that will be handled by our client side error callback functions.

Note: The implementation is just to demonstrate the client-server communication. The server side code is not optimized or refactored in any way.

Now when we run the application, we can see the result as:


Passing and Returning Objects to Client Side from Server Side

Now we have seen how can we pass the data to and from client side to server side. This section specially discusses the possibility of using JSONso that if I have to return more than one value to client side then I can encapsulate all these values in a class, serialize it in JSONformat and return it to client side.

Let us have a simple class that encapsulates two integer fields.

We have to decorate/adorn this class with DataContractattribute so that it can be serialized in JSONformat. The members that need to be included in JSONformat have to be public and decorated with DataMemberattribute.

Now let is write a simple server side function that creates an object of this type and returns the JSONrepresentation string of this object.

Now from the client side all we need to do is to call this method. The callback that handles the success will have to evaluate this JSONstring to a javascript object using eval method and then display the result to the user. So let us see the JavaScript code that calls this method, handles the success and handles the error.

Now when we call this method, the object will be created on server side and will be returned to the client side as JSON.


This functionality can also be extended to get some values from the client side, create an object based on these values on server, perform some operation on the object and then return the updated object in JSONformat.

TO see this let us implement the logic of incrementing a pairObject using the overloaded operator on server side. This will be called from client and result will be shown using a JSON.

The server side method.

Client side JavaScript

When we run it we can see the result on client side as:


Calling a Web Service from JavaScript

Now we have seen how to call a simple server side method, how to call a server side method with some values, how to get return value from server side and how to get multiple return values in form of JSON.

One more important piece of functionality is to be able to call web services from javascript. To see how it can be done, let us create a simple sample web service that performs an addition.

This service is decorated/adorned with the ScriptServiceattribute to make it possible to be called from JavaScript.

Now to be able to call this service from client side we need to add a reference to this service in the ScriptManager. This can be done as:

Once we have this service added in the list of ScriptManagerservices, we can simply call the methods of this service as:

Above code shows the function to invoke the service i.e. InvokeService. The callback function that will be called on success i.e. OnServiceSuccess. And the callback method that will be called on error i.e. OnserviceFailure. Let us now run the application to see how this service can be invoked from javascript.


One more thing to notice here is that we have used userContexthere to pass some data from the caller of the service to the callback method. userContextis useful if we need to pass some data from calling methods to the callback. Because the callbacks can be called for various methods and even multiple times for same method. userContextcan be used to identify them.

Note: Downloading the sample code and running it will be very helpful because this article show code snippets of C#, JavaScript and ASPX markup. So to get the complete picture please refer to the sample code.

Point of interest

So we have seen how we can call the server side methods from JavaScript using ASP.NET Ajax framework. We have also seen how we can consume web services from javascript. This article was written from a beginner’s perspective. I hope this has been informative.

Download sample code for this article: AJAXSampleApp3