Friday, June 1, 2012

Calling a WCF Service from Client Side( JavaScript ) ( Ajax Enabled WCF Service )

In this post I will show you how to call the WCF service from the client side. First of all create a new Asp.net empty website. From the add new item dialog box add a new web form. In this web form add two text boxes and a label control. In text boxes we will take the numbers from the user and in label we will show the sum of the numbers, also add a button control. The aspx source code looks like:
<asp:TextBox ID="txtNum1" runat="server" ClientIDMode="Static" />  
 <br />  
 <asp:TextBox ID="txtNum2" runat="server" ClientIDMode="Static" />  
 <br />  
 <input name="ButtonCalculate" type="button" value="Sum"  
 onclick="ButtonCalculate_onclick()" />  
 <br />  
 <asp:Label ID="lblResult" runat="server" ClientIDMode="Static" ></asp:Label>  
Now after  this from the add new item dialogue box add a new Ajax enabled WCF service to your solution. It will add two files one with .svc and one with .cs extension. Now open the .cs file and write a function for calculating the sum of two numbers. The code is below:
[ServiceContract(Namespace = "")]  
 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]  
 public class ServiceAddNumbers  
 {       
      [OperationContract]  
      public int AddNumbes(int a,int b)  
      {           
           return a+b;  
      }        
 }  
In the above code namespace attribute is not necessary. We created a function AddNumbers which takes two integers and return its sum.
Now we will look at how to call this service from the client side. First add a script manager to the page. In source of Script Manager add a services tag and inside it add a reference to the wcf service. The code is below:
<asp:ScriptManager ID="ScriptManager1" runat="server">  
 <Services>  
     <asp:ServiceReference Path="~/ServiceAddNumbers.svc" />  
 </Services>  
 </asp:ScriptManager>  
After this we will write a JavaScript function to call the service. The function code is below :
<script language="javascript" type="text/javascript">  
     function ButtonCalculate_onclick() {  
       var svc = new ServiceAddNumbers;  
       svc.AddNumbes(txtNum1.value, txtNum2.value, onSuccess, onFail, null);  
       function onSuccess(result) {         
         lblResult.innerText = result;  
       }  
       function onFail(result) {  
         alert(result);  
       }            
 }  
   </script>  
The svc.AddNumbers function took five parameters first and second are the numbers, onSuccess function is called on successfully calling the service and onFail if an error occured and last parameter is usercontext set it to null.
Now the code is completed. Just run it add two numbers and it will show the sum of two numbers in the label control.

Download the complete Visual Studio Solution from below link:
Calling WCF Service from Client Side

Thanks.

No comments:

Post a Comment