Calling WCF Service Using ScriptManager

Background

In this article we will learn how to call a WCF service using the ScriptManager. There is often a need to call a web service using Ajax but it's very time consuming and requires a lot of something to script and to write so to avoid this we can also call a WCF service using the ScriptManager. So let us learn how to do the call step-by-step so beginners also can understand.
 
Requirements to understand this tutorial 
 
If you are a beginner and you need to understand what a web service is, to learn about it refer to the following article of mine:
  1. Creating WCF Service

I hope you read it if you are unfamiliar with WCF services, so I will briefly define what a WCF service and ScriptManager are.

Windows Communication Foundation (WCF)
 
WCF is a library for applications of various platforms or the same platform to communicate over the various protocols such as TCP, HTTP, HTTPS and so on.
 
ScriptManager
 
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 a web service, to handle errors and so on. So let us demonstrate this concept with a web application.

Step 1
 
Create a WCF Service as in the following:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New Project" - "C#" - "ASP.NET Empty Web Application" (to avoid adding a master page).
  3. Provide the web site a name such as "CallingWCFServiceUsingScriptManager" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item". You will see the WCF service template then click on "Add".
Step 2

Add a web page to the new web application as in the following:
  1. Right-click on Solution Explorer - "Add New Item" - you see the Web Form  template then click on Add 
  2. Now drag and drop one ScriptManager, two textBoxes and one button on the Default.aspx Page. Then the source code of the Default.aspx page will look as follows:
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>    
  2.     
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">    
  4. <html xmlns="http://www.w3.org/1999/xhtml">    
  5. <head id="Head1" runat="server">    
  6.     <title></title>    
  7.         
  8. </head>    
  9. <body bgcolor="black">    
  10.     <form id="form1" runat="server">    
  11.      
  12.     
  13.     <br />    
  14.     <h2 style="color: #808000; font-size: medium; font-weight: bolder;">    
  15.         Article by vithal wadje</h2>    
  16.     <br />    
  17.     <br />    
  18.     <br />    
  19.     <table style="width: 73%; color: White;">    
  20.         <tr>    
  21.             <td>    
  22.                 Enter First Number    
  23.             </td>    
  24.             <td>    
  25.                 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>    
  26.             </td>    
  27.         </tr>    
  28.         <tr>    
  29.             <td>    
  30.                 Enter Second Number    
  31.             </td>    
  32.             <td>    
  33.                 <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>    
  34.             </td>    
  35.         </tr>    
  36.         <tr>    
  37.             <td>    
  38.             </td>    
  39.             <td>    
  40.             </td>    
  41.         </tr>    
  42.         <tfoot>    
  43.             <tr>    
  44.                 <td>    
  45.                 </td>    
  46.                 <td colspan="3">    
  47.                     <input id="Savebtn" type="button" value="Calculate" onclick="GetDetails();" />    
  48.                 </td>    
  49.             </tr>    
  50.         </tfoot>    
  51.     </table>    
  52.     </form>    
  53. </body>    
  54. </html>   

Now  the Solution Explorer will look such as follows:

 
In the preceding Solution Explorer you have seen that a Service.svc file is added and out of that there is a Default.aspx page from which we will call the WCF service using the Script Manager and another is a .svc file that is a our WCF service.
 
Step 3

Create a method in the Service.svc file as in the following:
  1. public class Service  
  2.    {  
  3.       [OperationContract]  
  4.        public int GetAddition(int a, int b)  
  5.        {  
  6.            //returning sum of given input numbers    
  7.            return a + b;  
  8.        }    
  9.         
  10.    } 
 Step 4

To allow calling a WCF service from JavaScript, jQuery or ScriptManager, we need to add the following line at the top of the class name. We also need to specify the namespace. The namespace may be any name that is used to uniquely identify the Service as in the following:
  1.  [ServiceContract(Namespace = "AdditionService")]
  2.  [AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]

After adding the preceding line, the Service class will look as follows:

  1. [ServiceContract(Namespace = "AdditionService")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  2. public class Service  
  3.     {  
  4.        [OperationContract]  
  5.         public int GetAddition(int a, int b)  
  6.         {  
  7.             //returning sum of given input numbers    
  8.             return a + b;  
  9.         }    
  10.          
  11.     } 
Note: the namespace name in ServiceContract attribute that is used to call service from the script must be provided.

In the code above, I have Implemented one method named GetAddition that takes the two integer type parameters that are a,b and returns the sum of the two integer variables. 
 
 Step 5

Let us see the UI of the .aspx page:
 
 
 
In the preceding UI you saw that there are two textboxes that accept the two numbers and there is the calculate HTML button that calls the JavaScript function to call the web service using the script manager.
 
Step 6

Refer to the Service Path using the Script Manager as in the following:
  1. <asp:ScriptManager ID="ScriptManager1" runat="server">    
  2.       <Services>    
  3.           <asp:ServiceReference Path="~/Service.svc" />    
  4.       </Services>    
  5.   </asp:ScriptManager>   
In the preceding source code, is a Services tag under the Script Manager control that allows setting of the WCF service reference. After adding the service reference the Web.config will look as follows:
  1. <system.serviceModel>  
  2.     <behaviors>  
  3.         <endpointBehaviors>  
  4.             <behavior name="CallingWCFUsingScriptManager.Service1AspNetAjaxBehavior">  
  5.                 <enableWebScript />  
  6.             </behavior>  
  7.         </endpointBehaviors>  
  8.     </behaviors>  
  9.     <serviceHostingEnvironment aspNetCompatibilityEnabled="true"  
  10.         multipleSiteBindingsEnabled="true" />  
  11.     <services>  
  12.         <service name="CallingWCFUsingScriptManager.Service">  
  13.             <endpoint address="" behaviorConfiguration="CallingWCFUsingScriptManager.Service1AspNetAjaxBehavior"  
  14.                 binding="webHttpBinding" contract="CallingWCFUsingScriptManager.Service" />  
  15.         </service>  
  16.     </services>  
  17. </system.serviceModel> 
 
Step 7

Create a JavaScript function to call the service method as in the following:
  1.     function GetDetails()   
  2.        {  
  3.            //reads the values to textboxes    
  4.            var a = document.getElementById('TextBox1').value;  
  5.            var b = document.getElementById('TextBox2').value;  
  6.   
  7.            // the value to  method    
  8.           //Namespace + class Name + Method Name
             AdditionService.Service.GetAddition(a, b, SuccessCallback, OnfailureCallback);
  9.   
  10.        }   
In the code above, I have read the values of two textboxes and stored them in the a and b variables and then I am ing those variables to the WCF service method that takes the four parameters that are input parameters, SuccessCallback, OnfailureCallback and usercontext. I will briefly explain what they are.
  • OnSucess: returns the results after successfully executing the WCF services method, this parameter is optional.
  • Onfailed: If the WCF service method fails to execute then it returns the error details, it accepts the error object as a  parameter, this parameter is optional.
  • usercontext: This is used to provide some additional information, this parameter is optional.

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

OnSuccess
  1. //returns output from service     
  2.        function SuccessCallback(AddResult)   
  3.        {  
  4.            //displaying output on alertbox     
  5.            alert(AddResult);  
  6.   
  7.   
  8.        } 
 onfailed
  1. //returns the error after WCF  service failed to execute     
  2.        function OnfailureCallback(error)   
  3.        {  
  4.            //displaying error on alert box    
  5.            alert(error);  
  6.   
  7.        }   
Now after adding the preceding three functions under the <Head> tag of the default.aspx page the function will look as follows:
  1. <script type="text/javascript">  
  2.   
  3.       function GetDetails()   
  4.       {  
  5.           //reads the values to textboxes    
  6.           var a = document.getElementById('TextBox1').value;  
  7.           var b = document.getElementById('TextBox2').value;  
  8.   
  9.           // the value to  method    
  10.            //Namespace + class Name + Method Name
             
    AdditionService.Service.GetAddition(a, b, SuccessCallback, OnfailureCallback); 
  11.   
  12.       }  
  13.       //returns output from service     
  14.       function SuccessCallback(AddResult)   
  15.       {  
  16.           //displaying output on alertbox     
  17.           alert(AddResult);  
  18.   
  19.   
  20.       }  
  21.       //returns the error after WCF  service failed to execute     
  22.       function OnfailureCallback(error)   
  23.       {  
  24.           //displaying error on alert box    
  25.           alert(error);  
  26.   
  27.       }    
  28.   </script> 
 Step 8

Now call the GetDetails() function on the Calculate HTML input button click. That calls the WCF service method without postback as in the following:
  1. <input id="Savebtn" type="button" value="Calculate" onclick="GetDetails();" />   
Now click F5 to run the application. Enter some number into the two textboxes and click on the calculate button, it will show the following output:
 
 
 
In the preceding image the output is returned from the WCF service as 24. Now it's clear that we can also call the WCF service using the Scriptmanager and we will avoid the time of writing JSON code to call the service.
 
Note:
  • For detailed code please download the Zip file attached above.
Summary

From all the examples above we have seen how to call a WCF service using the script manager and how to reduce the code required to call a service using 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.
 


Similar Articles