Home > DotNet, Javascript > How to call serverside function from client side javascript in ASP.Net?

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

  1. Create a aspx page with three textboxes and a button control.
  2. User enter two numbers in first two textboxes and press calculate button.
  3. We are fetching entered values and calling a serverside funtion by passing this values.
  4. In the server side function find the sum and return the result.
  5. 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.

About these ads
  1. November 10, 2011 at 9:06 am

    Nice post.
    That is exactly what i was looking for!
    Thank you very much!!!!

  2. November 10, 2011 at 12:16 pm

    Thank You..
    Please keep visiting my blogs.. :)

  3. February 15, 2012 at 10:42 am

    But It is not working .
    Microsoft JScript runtime error: ‘PageMethods’ is undefined-This error is coming while i am running this code.

  4. February 15, 2012 at 12:04 pm

    Hi Prabhu,
    You have to put EnablePageMethods=”true” inside the script manager as mentioned in the post.

  5. Guven
    February 21, 2012 at 10:14 pm

    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!

  6. MiRu
    February 24, 2012 at 5:05 pm

    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)

  7. February 25, 2012 at 11:32 am

    Miru,
    Thank you for your comments and valid suggetion.
    Please keep visiting blog..

    Guven,
    Your issue is solved?

  8. March 23, 2012 at 1:28 pm

    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

  9. March 23, 2012 at 10:48 pm

    Hi Mayank,
    Please check whether you put EnablePageMethods=”true” inside the script manager as mentioned in the post.

  10. Mayank Gupta - Taurus Vs Pisces, lets see....
    March 24, 2012 at 2:08 pm

    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.

  11. Mayank Gupta - Taurus Vs Pisces, lets see....
    March 24, 2012 at 2:09 pm

    can u pls send me a small sample of thos page in zip format so that I may test this on my machine.

  12. Mayank Gupta - Taurus Vs Pisces, lets see....
    March 24, 2012 at 2:16 pm

    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.

  13. saurav
    June 30, 2012 at 8:26 am

    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.

  14. June 30, 2012 at 7:22 pm

    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 :)

  15. October 26, 2012 at 6:11 pm

    it works ! great…
    thanks.

  16. October 27, 2012 at 4:39 pm

    Hi Altaf,
    Thanks for your comments..
    Keep visiting our blog

  17. keshav patel
    March 12, 2013 at 10:24 am

    thanks for ur post it helps me lot

  18. brahmendra
    May 12, 2013 at 11:27 am

    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.

  19. benson
    May 31, 2013 at 1:57 pm

    Hi Sir thanks sharing

    on my end am using VB and getting this error

    Microsoft JScript runtime error: ‘PageMethods’ is undefined’

  20. May 31, 2013 at 2:31 pm

    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

  21. adesupo
    June 17, 2013 at 10:48 pm

    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..

  22. June 18, 2013 at 9:40 am

    Hi adespo,

    Thank you for your valuable suggestion..
    Keep visiting blog :)

  23. Ravindra
    July 2, 2013 at 3:30 pm

    Thanks Guys it is working fine

  24. January 22, 2014 at 6:19 am

    Thanks ffor sharing such a pleasant thought, article is nice, thhats why
    i have read it fully

  25. Robert Demaree
    April 4, 2014 at 1:52 am

    How would I get to see the WHOLE example? Part of the code is truncated on this page.

  1. July 5, 2014 at 10:51 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 43 other followers

%d bloggers like this: