Wednesday, 11 July 2018

Calling WCF Services Using jQuery

Here, we will call a simple WCF service using a POST request and then display the received data in a table. To do that I have tried looking at tutorials around the web. I show many solutions to call a WCF Service by jQuery AJAX methods. But I did not find a simple way as I am describing here. This article initially starts with a SQL Database table. As the article progresses it explains how to create a WCF service and access this service on an ASP.NET page using jQuery AJAX methods. And also this article will be very helpful for those who are looking for a solution for that type of problem like we do not want to reload the page again and again.
For example if you select an item from a DropDownList or other control on the same page then that can cause a loss of data.
jQuery AJAX method
All jQuery AJAX methods use the ajax() method. The ajax() method performs an Asynchronous HTTP (AJAX) request.
Syntax
  1. $.ajax({ Parameter1, parameter2..........})  
or

  1. $.ajax({  
  2.     type:,  
  3.     contentType:,  
  4.     url:, data:,     
  5.     async,......  
  6. });  
The following is the description of some important parameters used by the "$.ajax" method:
Type: The default value of type is GET. A string defining the HTTP method to use for the request (GET or POST).
  • GET: Requests data from a specified resource
  • POST: Submits data to be processed to a specified resource
ContentType: When sending data to the server, use this content type. The default is "application/x-www-form-urlencoded".
URL: A string containing the URL to which the request is sent. The default is the current page.
Data: Data defines the data to be sent to the server. 
async: The default is true. A Boolean value indicating whether the request should be handled asynchronously or not. 
Success: A callback function that is executed if the request succeeds.
To read More: jQuery AJAX Introduction
Now, let's see how to do that.
First we create a table named PersonalDetail with the columns Name, LastName and Email. Now insert data into the table. The table is as in the following:.
table
The back-end database work is now done.
Creating WCF Service
Now you need to create a WCF Service:
  • Go to Visual Studio 2012
  • New-> Select a web
Now click on the project and select WCF Service Application and provide a name for the service:

For selecting data from the database you need to write the following code in the IService1.cs file that contains the two sections:
  1. OperationContract
  2. DataContract
The OperationContract section is used to add service operations and DataContract is used to add types to service operations.

Iservice1.cs File
Now we create a function in the OperationContract section of the Iservice1.cs file:
  1. [ServiceContract]    
  2. public interface IService    
  3. {    
  4.     [OperationContract]     
  5.     string GetData();    
  6. }  
Service.cs File

In this file we define the definition of the function GetData. And replace the code with the following:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.Data.SqlClient;  
  5. using System.ServiceModel.Activation;  
  6. using System.Data;  
  7. using System.Web.Script.Serialization;  
  8.   
  9. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]  
  10. public class Service : IService  
  11. {  
  12.     public string GetData()  
  13.     {  
  14.         SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Test;User ID=sa;Password=Password$2");  
  15.         con.Open();  
  16.         SqlCommand cmd = new SqlCommand("Select * from PersonalDetail", con);  
  17.         SqlDataAdapter sda = new SqlDataAdapter(cmd);  
  18.         DataSet ds = new DataSet();  
  19.         sda.Fill(ds);  
  20.         cmd.ExecuteNonQuery();  
  21.         con.Close();  
  22.         DataTable dt = ds.Tables[0];  
  23.         JavaScriptSerializer serializer = new JavaScriptSerializer();  
  24.         List<Dictionary<stringobject>> rows = new List<Dictionary<stringobject>>();  
  25.         Dictionary<stringobject> row;  
  26.         foreach (DataRow dr in dt.Rows)  
  27.         {  
  28.             row = new Dictionary<stringobject>();  
  29.             foreach (DataColumn col in dt.Columns)  
  30.             {  
  31.                 row.Add(col.ColumnName, dr[col]);  
  32.             }  
  33.             rows.Add(row);    
  34.         }  
  35.         return serializer.Serialize(rows);  
  36.     }  
  37. }  
Now you need to specify the attributes on the server type class for ASP.NET compatibility mode, so that the WCF service works as a normal ASMX service and supports all existing ASP.NET features. By setting compatibility mode, the WCF service will need to be hosted on IIS and communicate with its client application using HTTP. Now add the following code under the <system.serviceModel> section of web.config File.
  1. <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>  
  2.     <services>  
  3.       <service name="Service" behaviorConfiguration="ServiceBehavior1">  
  4.         <endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="EndPointBehavior"/>  
  5.         <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>  
  6.       </service>  
  7.     </services>  
  8.     <behaviors>  
  9.       <serviceBehaviors>  
  10.         <behavior name="ServiceBehavior1">  
  11.           <serviceMetadata httpGetEnabled="true"/>  
  12.           <serviceDebug includeExceptionDetailInFaults="true"/>  
  13.         </behavior>  
  14.       </serviceBehaviors>  
  15.       <endpointBehaviors>  
  16.         <behavior name="EndPointBehavior">  
  17.           <enableWebScript/>  
  18.         </behavior>  
  19.       </endpointBehaviors>  
  20.     </behaviors>  
Testing the Service
Once you are done with creating the WCF service, Press F5 to run the service. A WCF Test Client form will be displayed and it will load the service.
Testing the Service
Now add the following jQuery code snippets in the script tag for calling the service.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestService.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.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head>  
  7.     <title>Call WCF Service using jQuery</title>  
  8.     <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>  
  9.     <script type="text/javascript">  
  10.         $(function () {              
  11.             $.ajax({  
  12.                 type: "POST",  
  13.                 contentType: "application/json; charset=utf-8",  
  14.                 url: 'Service.svc/GetData',  
  15.                 success: function (data) {  
  16.                     $($.parseJSON(data.d)).each(function (index, value) {  
  17.                         $("#TableID").append("<tr><td>" + value.Name + "</td><td>" + value.LastName + "</td><td>" + value.Email + "</td></tr>");  
  18.                     });  
  19.                 },  
  20.                 error: function (result) {  
  21.                     alert(result);  
  22.                 }  
  23.             });  
  24.   
  25.         });  
  26.         // });  
  27.     </script>  
  28.   
  29. </head>  
  30. <body>  
  31.     <form id="form1" runat="server">  
  32.         <table id="TableID" cellpadding="0" cellspacing="0" border="1"  width="400px" >  
  33.             <tr>  
  34.                 <td style="background-color: green; color:white">Name</td>  
  35.                 <td style="background-color: green; color:white">LastName</td>  
  36.                 <td style="background-color: green; color:white">Email</td>  
  37.             </tr>  
  38.         </table>  
  39.     </form>  
  40. </body>  
  41. </html>  
In the code above I have used the $.parseJSON() method for JSON Data.
  1.  $($.parseJSON(data.d)).each(function (index, value) {    
  2.       $("#TableID").append("<tr><td>" + value.Name + "</td><td>" + value.LastName + "</td><td>" + value.Email + "</td></tr>");    
  3. });  
When you run the application, it will call the service, fetch data and display in a tabular format as shown in the following figure.

run the application

No comments:

Post a Comment