With this post I would show how to call server side method from client side. Here we will use jQuery to utilize the Ajax Capabilities which will help us to get/post data to/from server Asynchronously. There are many methods available to perform an async callback to the server. Here I will show a simple example as in how to call a code behind Webmethod.
For simplicity I would be calling the code behind method on a Button Click. Here is the code:
Code Behind (C#):
In the above code, the aspx markup contains a button on click of which we would call the server side method named ServerSideMethod(). The div would show the message returned from the server. When you run the code above and click the button, it would the div would show the message "Message from server".
If you want to send parameters to your code behind method, you would change the line 8 in the above jQuery code as:
With the above line I would be sending a parameter with value as 1 to the server side method.
The method would change as:
The output will now be:
Message from server with parameter:1
You could also call any webmethod method in your webservice by changing the url in the jQuery as:
where WebService1 is your webservice and ServerSideMethod is your webmethod in WebService1.
Here is another example of how to do so: