How to call serverside function from client side javascript in ASP.Net?
Call ASP.Net/C# function using Javscript
Usually in ASP.net platform, server side functions (all codes written in asp.net,C#) are executing from the server side and all client side funtions (javascript,jquery,ajax) are executing from the client side. Obviously client side functions are too faster than the server side because there is no need to go upto server, will running from the browser itself.
But we are unable to written all functions in client side to get good performance. But for this technique, there is some tips can be used. What we are going to do is, we are writing a server side code in ASP.Net,C# and call these functions from client side using javascript and ajax.
Steps to Calling ServerSide method from javscript

- Create a aspx page with three textboxes and a button control.
- User enter two numbers in first two textboxes and press calculate button.
- We are fetching entered values and calling a serverside funtion by passing this values.
- In the server side function find the sum and return the result.
- In client side’s succes event, getting result from the server and displayed to third textbox.
Step 1 :
Create a aspx page with controls, two textboxes for entering the numbers, one button for find the sum of number and a one more text box to display the result.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Result.aspx.cs" Inherits="testWebApp.Result" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true"> </asp:ScriptManager> <div> <table> <tr> <td> Number1: </td> <td> <asp:TextBox ID="txt1" runat="server"></asp:TextBox> </td> </tr> <tr> <td> Number2: </td> <td> <asp:TextBox ID="txt2" runat="server"></asp:TextBox> </td> </tr> <tr> <td> Sum: </td> <td> <asp:TextBox ID="txtSum" runat="server"></asp:TextBox> </td> </tr> <tr> <td> <asp:Button ID="btnSum" runat="server" Text="Sum" OnClientClick="CallSum();return false;" /> </td> </tr> </table> </div> </form> </body> </html>
Step 2
In code behind, write a web method to access two parameters and return the result. In the function we added parameters and return the result.
protected void Page_Load(object sender, EventArgs e)
{
}
/// <summary>
/// Server side function Sum
/// </summary>
/// <param name="arg1">arg1</param>
/// <param name="arg2">arg2</param>
/// <returns>result(sum)</returns>
[System.Web.Services.WebMethod]
public static int Sum(int arg1, int arg2)
{
/* On server side we can do any thing. Like we can access the Session.
* We can do database access operation. Without postback.
*/
try
{
return arg1 + arg2;
}
catch (Exception ex)
{
throw ex;
}
}
Step 3
Create a javscript method in aspx page to get input textboxes values and call serverside function. Here itself we decalre a success and failure event, for getting the event from the server after the current function executed.
<script language="javascript" type="text/javascript">
<!--
// Javascript function
function CallSum() {
//Get the controls
var txt1 = $get("txt1");
var txt2 = $get("txt2");
var txtresult = $get("txtSum");
//Call server side function
PageMethods.Sum(txt1.value, txt2.value, OnCallSumComplete, OnCallSumError, txtresult);
/*Server side function get the 2 arguments arg1 and arg2. We are passing txt1.value and txt2.value
for that. OnCallSumComplete is callback function for complete successfully. OnCallSumError is callback
function on error. txtresult is usercontext parameter.
OnCallSumComplete,OnCallSumError,txtresult are optional parameters.
If server side code executed successfully then OnCallSumComplete will call.
If server side code do not executed successfully then OnCallSumError will call.
*/
}
// Callback function on complete
// First argument is always "result" if server side code returns void then this value will be null
// Second argument is usercontext control pass at the time of call
// Third argument is methodName (server side function name) In this example the methodName will be "Sum"
function OnCallSumComplete(result, txtresult, methodName) {
//Show the result in txtresult
txtresult.value = result;
}
// Callback function on error
// Callback function on complete
// First argument is always "error" if server side code throws any exception
// Second argument is usercontext control pass at the time of call
// Third argument is methodName (server side function name) In this example the methodName will be "Sum"
function OnCallSumError(error, userContext, methodName) {
if (error !== null) {
alert(error.get_message());
}
}
// -->
</script>
Project is ready for call server sided functions from client side using javascript. Run the application and enter two numbers in first and second textboxes then press calculate button, the we can show that result is displayed in third box without any page postback. If we enterd alphabets instead of numbers, from the server it will happening error and ‘failure’ event occurred in the javascript will alert the details of the error.
Nice post.
That is exactly what i was looking for!
Thank you very much!!!!
Thank You..
Please keep visiting my blogs..
But It is not working .
Microsoft JScript runtime error: ‘PageMethods’ is undefined-This error is coming while i am running this code.
Hi Prabhu,
You have to put EnablePageMethods=”true” inside the script manager as mentioned in the post.
Hi,
It is not working when I am using it within a javascript pop up window. It says “CallSum is undefined”. When there is a postback in a pop up window, it automatically closes the window. I have used your code to eliminate postback but did not help. Any other idea? Thanks!
Nice posting.
Thank you!!!!!
Guven,
Check to see if you have the word “static” in your code as :
[System.Web.Services.WebMethod]
public static void YourFunction(type param)
Miru,
Thank you for your comments and valid suggetion.
Please keep visiting blog..
Guven,
Your issue is solved?
this script is not working bro. I have put the exact code as you mentioned but it is not taking the values from textboxes even after checking all IDs etc. If you can post a link of the same project in a zipped form here or at my mail id mayank.gpt1@gmail.com , will be a great gesture
Thanks.
mayank
Hi Mayank,
Please check whether you put EnablePageMethods=”true” inside the script manager as mentioned in the post.
yes bro I had put the same code inside. Its visual studio 2005, does version of vs matters for this coz I think ajax is not inbuilt in 2005 version of vs.
can u pls send me a small sample of thos page in zip format so that I may test this on my machine.
one more problem is troubling me since a long time.
How can I create subdomains through web page directly on my localhost.
Like…
abc.localhost.com
xyz.localhost.com
I’v tried many samples from net but most of the time application shows error in the web config file.
hii, you have written the best post i read from last two days
if possible please tell me how can i pass arguments to javascript function on link click and pass that argument to a pagemethod from that js function and then retrive the return and show it on page. thanx a lot.
Hi Sourav,
Thank you for visiting my blog and your valuable comments.
In the above example we are passing two arguments from javascript method and these two parameters are retrieving from server side page method “Sum(int arg1, int arg2)”.
You can use same way for passing argument from javascript and you can display this parameters in your page.
Please check and let me know if you have any more doubts.
Once again thanks and please keep visiting my blog
it works ! great…
thanks.
Hi Altaf,
Thanks for your comments..
Keep visiting our blog
thanks for ur post it helps me lot
HI SIR,
you are creating a web method in .aspx page.now this method is working as a web service method. please answer this question.if this method is working as a web service method ,how handler knows this method is web method because handler knows .asmx as a webservice.
Hi Sir thanks sharing
on my end am using VB and getting this error
Microsoft JScript runtime error: ‘PageMethods’ is undefined’
Hi Benson,
Many possible reasons :
Make sure to Enable Page methods for the Script Manager , this can be done by setting its EnablePageMethods proeprty to true .
Make sure that you correctly configured your website to work with asp.net ajax.
Make sure that the Page method function is Public and Static ( or shared in VB)
Please try and let me know.
Thanks,
Tuvian
This is very helpful. I was able to adapt your method to solve my problem. however, I modify OnCallSumComplete, I am putting my result in asp:label control. using txtresult.value did not work. so I modified the function as thus:
function OnCallSumComplete(result, txtresult, methodName) {
//Show the result in txtresult
txtresult.value = result;
}
Changed to
function OnCallSumComplete(result, txtresult, methodName) {
//Show the result in txtresult
var output = document.getElementById(“lbwords”);
output.innerText = result;
}
this works for me.
Thanks..
Hi adespo,
Thank you for your valuable suggestion..
Keep visiting blog