Click here to Skip to main content
Click here to Skip to main content
Articles » Web Development » Ajax » General » Downloads
 
Add your own
alternative version

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

, 14 Jan 2013
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.
AJAXSampleApp3.zip
AJAXSampleApp3
App_Code
App_Data
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>AJAX server side function demo</title>
    
    <script type="text/javascript">
    
    // Javascript methods to get the dummy message
    function CallServerMethod()
    {
        // call the server side method here
        PageMethods.GetMessage(OnSuccess);       
    }
    
    function OnSuccess(result)
    {
        alert(result);
    }
    
    // Javascript methods to perform arithmentic operations
    function CallServerAdd()
    {
        var a = document.getElementById('TextBox1').value;
        var b = document.getElementById('TextBox2').value;
        PageMethods.Add(a, b, OnResult,OnError);
    }
    
    function CallServerSub()
    {
        var a = document.getElementById('TextBox1').value;
        var b = document.getElementById('TextBox2').value;
        PageMethods.Sub(a, b, OnResult, OnError);
    }
    
    function CallServerMul()
    {
        var a = document.getElementById('TextBox1').value;
        var b = document.getElementById('TextBox2').value;
        PageMethods.Mul(a, b, OnResult, OnError);
    }
    
    function CallServerDiv()
    {
        var a = document.getElementById('TextBox1').value;
        var b = document.getElementById('TextBox2').value;
        PageMethods.Div(a, b, OnResult, OnError);
    }
    
    // Function to handle the success
    function OnResult(result, userContext,method)
    {
        var resultMsg = "Result from Method [" + method +"] is: " + result;
        alert(resultMsg);         
    }
    
    // function to handle the error
    function OnError(error, userContext, method)
    {
        if(error != null)
        {
            var resultMsg = "Error from Method [" + method +"] is: '" + error.get_message() + "'";
            alert(resultMsg);
        }
    }
    
    // Functions to handle the JSON objects to and from the server    
    function CallSamplePair()
    {
        PageMethods.GetSamplePairOfInts(OnJSONGetSuccess, OnJSONGetFailure);       
    }
        
    function OnJSONGetSuccess(result, userContext, method)
    {
        if(result != null)
        {
            var PairOfInts = eval('('+ result + ')');
        
            var resultMsg = "Pair from Method [" + method +"] is: (" + PairOfInts.Value1 + ", " + PairOfInts.Value2 + ")";
            alert(resultMsg);         
        }
    }
    
    function OnJSONGetFailure(error, userContext, method)
    {
        if(error != null)
        {
            var resultMsg = "Error from Method [" + method +"] is: '" + error.get_message() + "'";
            alert(resultMsg);
        }
    }
    
    // here we will pass JSON to the server
    function IncrementPair()
    {
        PageMethods.IncrementPairOfInts(document.getElementById('TextBox3').value, 
                                        document.getElementById('TextBox4').value, 
                                        OnJSONGetSuccess, OnJSONGetFailure);                
    }
    
    // This section will handle the calls to webservice from javascript
    function InvokeService()
    {
        TestService.Add(document.getElementById('TextBox5').value,
                        document.getElementById('TextBox6').value,
                        OnServiceSuccess, OnserviceFailure, 'Webservice.Add');       
    }
    
    function OnServiceSuccess(result, userContext, method)
    {
        var resultMsg = "Result from Method [" + userContext +"] is: " + result;
        alert(resultMsg);         
    }
    
    function OnserviceFailure(error, userContext, method)
    {
        if(error != null)
        {
            var resultMsg = "Error from Method [" + userContext +"] is: '" + error.get_message() + "'";
            alert(resultMsg);
        }
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        <Services>
            <asp:ServiceReference Path="TestService.asmx" />
        </Services>
        </asp:ScriptManager>
        Last Postback on: &nbsp;<asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
        <br />
        <div>        
            <asp:Button ID="Button1" runat="server" Text="Get Message" OnClientClick="CallServerMethod(); return false;" />        
            <br />
            <br />
            Simple Calculator<br />
            
            <table>
            <tr>            
            <td>
                A: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            </td>
            <td>
                B: <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            </td>
            </tr>
            </table>
            <br />
            <asp:Button ID="Button2" runat="server" Text="A+B" OnClientClick="CallServerAdd(); return false;" />
            &nbsp;
            <asp:Button ID="Button3" runat="server" Text="A-B" OnClientClick="CallServerSub(); return false;"  />
            &nbsp;
            <asp:Button ID="Button4" runat="server" Text="A*B" OnClientClick="CallServerMul(); return false;"  />
            &nbsp;
            <asp:Button ID="Button5" runat="server" Text="A/B" OnClientClick="CallServerDiv(); return false;"  /><br />
            <br />
            <br />
            Getting the Objects from Serverside<br />
            <br />
            <asp:Button ID="Button6" runat="server" Text="Get Sample PairOfInts" OnClientClick="CallSamplePair(); return false;" /><br />
            <br />
            Passing an object to the ServerSide and getting it incremented<br />
            <br />
            <table>
                <tr>
                    <td>
                        Value1:
                        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                    </td>
                    <td>
                        Value 2:
                        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
                    </td>
                </tr>
            </table>
            <br />
            <asp:Button ID="Button7" runat="server" Text="Increment this PairOfInts" OnClientClick="IncrementPair(); return false;" /><br />
            <br />
            Lets do an Add using a webservice<br />
            <br />
            <table>
                <tr>
                    <td>
                        A:
                        <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
                    </td>
                    <td>
                        B:
                        <asp:TextBox ID="TextBox6" runat="server"></asp:TextBox>
                    </td>
                </tr>
            </table>
        </div>
        <br />
        <asp:Button ID="Button8" runat="server" Text="Add using Service" OnClientClick="InvokeService(); return false;" />
    </form>
</body>
</html>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Rahul Rajat Singh
Software Developer (Senior)
India India
I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.
  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4
 
If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]
Follow on   Twitter   Google+   LinkedIn

| Advertise | Privacy | Mobile
Web04 | 2.8.140821.2 | Last Updated 14 Jan 2013
Article Copyright 2013 by Rahul Rajat Singh
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid