Calling Web Service Using ScriptManager


In this article we will learn how to call web service using the ScriptManager,their is often need to call web service using Ajax but its very time consuming and require lots to script to write so to avoid this we can also call web service using the ScriptManager.
So how to call let us learn step by step so beginners also can understand.
 Per-requirement to Understand this tutorial
If you are a beginner and you need to understand what a web service,so to learn about it refer my below article
  1. Introduction to Web Service with Example in ASP.Net

I hope you read it if you are unfamiliar with web services,so let us i briefly define what a web service and ScriptManager,

What is web services ?

A "web service is the communication platform between two different or  same platform  applications  that allows to use their web method."

 What is ScriptManager ?

Basically When we use any Ajax control then there is a requirement to use the ScriptManager to handle the Scripting on the client side; without the ScriptManager Ajax controls are not run but also ScriptManager is used to call web service ,to handle errors and on.
So let us demonstrate this concept which help of one web application as
Step 1:
Create a Web Service as
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New Project" - "C#" - "Empty Web Application" (to avoid adding a master page).
  3. Provide the web site a name such as "CallingWebServiceUsingScriptManager" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item" - you see the web service template then click on add
Step 2:

Add Web Page in Created Web application as
  1.  Right-click on Solution Explorer - "Add New Item" - you see the Web Form  template then click on add 
  2. Now drag in drop one ScriptManager,two textBoxes ,one button on Default.aspx Page ,then the source code of the Default.aspx page will be look like as follows


  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">  
  4. <html xmlns="">  
  5. <head runat="server">  
  6.     <title></title>  
  8. </head>  
  9. <body bgcolor="black">  
  10.     <form id="form1" runat="server">  
  11.     <asp:ScriptManager ID="ScriptManager1" runat="server">  
  12.         <Services>  
  13.             <asp:ServiceReference Path="~/WebService.asmx" />  
  14.         </Services>  
  15.     </asp:ScriptManager>  
  17.     <br />  
  18.     <h2 style="color: #808000; font-size: medium; font-weight: bolder;">  
  19.         Article by vithal wadje</h2>  
  20.     <br />  
  21.     <br />  
  22.     <br />  
  23.     <table style="width: 73%; color: White;">  
  24.         <tr>  
  25.             <td>  
  26.                 Enter First Number  
  27.             </td>  
  28.             <td>  
  29.                 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
  30.             </td>  
  31.         </tr>  
  32.         <tr>  
  33.             <td>  
  34.                 Enter Second Number  
  35.             </td>  
  36.             <td>  
  37.                 <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>  
  38.             </td>  
  39.         </tr>  
  40.         <tr>  
  41.             <td>  
  42.             </td>  
  43.             <td>  
  44.             </td>  
  45.         </tr>  
  46.         <tfoot>  
  47.             <tr>  
  48.                 <td>  
  49.                 </td>  
  50.                 <td colspan="3">  
  51.                     <input id="Savebtn" type="button" value="Calculate" onclick="GetDetails();" />  
  52.                 </td>  
  53.             </tr>  
  54.         </tfoot>  
  55.     </table>  
  56.     </form>  
  57. </body>  
  58. </html> 
Now  the solution explorer will look like as follows
 In the above solution explorer you have seen that in App code folder there is WebService class added and out of that there is Default.aspx page from which we will call web service using script Manager and another is .asmx file which is a our web service.
Step 3:

Create method in WebService.cs Class  as
  1.       [WebMethod]  
  2.     public int GetAddition(int a, int b)  
  3.     {  
  4.         //returning sum of given input numbers  
  5.         return a + b;  
  6.     } 
 Step 4:

To allow calling web service from JavaScript,Jquery or scriptManager,we need to uncomment the following line of web service which is  

  1. //To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.  
  3. [System.Web.Script.Services.ScriptService] 
 Now whole code of WebService.cs class will be look like as follows
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Services;  
  7. /// <summary>  
  8. /// Summary description for WebService  
  9. /// </summary>  
  10. [WebService(Namespace = "")]  
  11. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  12. // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   
  13. [System.Web.Script.Services.ScriptService]  
  14. public class WebService : System.Web.Services.WebService  
  15. {  
  17.     [WebMethod]  
  18.     public int GetAddition(int a, int b)  
  19.     {  
  20.         //returning sum of given input numbers  
  21.         return a + b;  
  22.     }  

In the above code, I have created one method named GetAddition which takes the two integer type parameter that is a,b and returns the sum of two integer variable.
Let us see the UI of .aspx Page
In the above UI you have seen that there two textboxes which accepts the two numbers and there is calculate HTML  button which calls the javascript function to call web service using script manager.
Step 5:

Refer Service Path using Script manager as

In the above source code ,there is Services tag under the script manager control which allows to set the web service reference,now click on pick url or above option to set the path of web service.
After setting the path of web service the script manager tag will be look like as follows.
  1. <asp:ScriptManager ID="ScriptManager1" runat="server">  
  2.     <Services>  
  3.   <%--  web service reference --%>  
  4.      <asp:ServiceReference Path="~/WebService.asmx"/>  
  5.     </Services>  
  6. </asp:ScriptManager> 
 Step 6:

Create JavaScript function to call service Method as
  1.       function GetDetails()   
  2.        {  
  3.        //reads the values to textboxes  
  4.            var a = document.getElementById('TextBox1').value;  
  5.            var b = document.getElementById('TextBox2').value;  
  7.            // the value to Web method  
  8.            WebService.GetAddition(a, b, SuccessCallback, OnfailureCallback);  
  10.        } 
 in the above code ,i have read the values of two textboxes and storing in a and b variable and after that i am ing those variable to the web service method which takes the four parameter which are input parameters,SuccessCallback,OnfailureCallback and usercontext as given in the following image.
In the above image you have seen that GetAddition methods takes the two parameter as input and additional to that it takes OnSucess,OnFailed,Usercontext parameters ,let us briefly i will explain what  they are ?
  • OnSucess -> this returns the results after successfully executing the web services method,this parameter is an optional.
  • Onfailed -> Due to the some reason web service method failed to execute then its returns the error details,it accepts the error object as a  parameter ,this parameter is an optional.
  • usercontext -> This is used to provide some additional information,this parameter is an optional.

 I hope you understand about the parameter details,now similarly we will create methods for OnSucess and onfailed as.

  1. //returns output from service   
  2.       function SuccessCallback(AddResult)  
  3.        {  
  4.        //displaying output on alertbox   
  5.           alert(AddResult);  
  8.       } 
  1. //returns the error after web service failed to execute   
  2.        function OnfailureCallback(error)   
  3.        {  
  4.        //displaying error on alert box  
  5.            alert(error);  
  7.        } 
 Now after adding above three function under the <Head> tag of default.aspx page the function will be look like as follows .
  1. <script type="text/javascript">  
  2.         function GetDetails()   
  3.         {  
  4.         //reads the values to textboxes  
  5.             var a = document.getElementById('TextBox1').value;  
  6.             var b = document.getElementById('TextBox2').value;  
  8.             // the value to Web method  
  9.             WebService.GetAddition(a, b, SuccessCallback, OnfailureCallback);  
  11.         }  
  13.         //returns output from service   
  14.         function SuccessCallback(AddResult)  
  15.          {  
  16.          //displaying output on alertbox   
  17.             alert(AddResult);  
  20.         }  
  21.         //returns the error after web service failed to execute   
  22.         function OnfailureCallback(error)   
  23.         {  
  24.         //displaying error on alert box  
  25.             alert(error);  
  27.         }  
  28.     </script> 
 Step 7:

Now call GetDetails() function on Calculate html input button click which calls web service method without postback as
  1. <input id="Savebtn" type="button" value="Calculate" onclick="GetDetails();" /> 
Step 8:

Now click F5 to run application,enter some number into two textboxes and click on calculate button ,it will shows the following output as
In the above Image the output is return from the web service as 400 now its clear that we can also call the web service using Scriptmanager and we will avoid time of to write JSON code to call service.
  • For detailed code please download the Zip file attached above.
From all the examples above we seen that how to call web service using script manager and how reduce the code which required to call service with the help of JSON. I hope this article is useful for all students and beginners. If you have any suggestion related to this article then please contact me.