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
- $.ajax({ Parameter1, parameter2..........})
or
- $.ajax({
- type:,
- contentType:,
- url:, data:,
- async,......
- });
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:.
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:
- OperationContract
- 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:
- [ServiceContract]
- public interface IService
- {
- [OperationContract]
- string GetData();
- }
Service.cs File
In this file we define the definition of the function GetData. And replace the code with the following:
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Data.SqlClient;
- using System.ServiceModel.Activation;
- using System.Data;
- using System.Web.Script.Serialization;
-
- [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
- public class Service : IService
- {
- public string GetData()
- {
- SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Test;User ID=sa;Password=Password$2");
- con.Open();
- SqlCommand cmd = new SqlCommand("Select * from PersonalDetail", con);
- SqlDataAdapter sda = new SqlDataAdapter(cmd);
- DataSet ds = new DataSet();
- sda.Fill(ds);
- cmd.ExecuteNonQuery();
- con.Close();
- DataTable dt = ds.Tables[0];
- JavaScriptSerializer serializer = new JavaScriptSerializer();
- List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
- Dictionary<string, object> row;
- foreach (DataRow dr in dt.Rows)
- {
- row = new Dictionary<string, object>();
- foreach (DataColumn col in dt.Columns)
- {
- row.Add(col.ColumnName, dr[col]);
- }
- rows.Add(row);
- }
- return serializer.Serialize(rows);
- }
- }
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.
- <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
- <services>
- <service name="Service" behaviorConfiguration="ServiceBehavior1">
- <endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="EndPointBehavior"/>
- <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
- </service>
- </services>
- <behaviors>
- <serviceBehaviors>
- <behavior name="ServiceBehavior1">
- <serviceMetadata httpGetEnabled="true"/>
- <serviceDebug includeExceptionDetailInFaults="true"/>
- </behavior>
- </serviceBehaviors>
- <endpointBehaviors>
- <behavior name="EndPointBehavior">
- <enableWebScript/>
- </behavior>
- </endpointBehaviors>
- </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.
Now add the following jQuery code snippets in the script tag for calling the service.
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestService.aspx.cs" Inherits="_Default" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>Call WCF Service using jQuery</title>
- <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
- <script type="text/javascript">
- $(function () {
- $.ajax({
- type: "POST",
- contentType: "application/json; charset=utf-8",
- url: 'Service.svc/GetData',
- success: function (data) {
- $($.parseJSON(data.d)).each(function (index, value) {
- $("#TableID").append("<tr><td>" + value.Name + "</td><td>" + value.LastName + "</td><td>" + value.Email + "</td></tr>");
- });
- },
- error: function (result) {
- alert(result);
- }
- });
-
- });
-
- </script>
-
- </head>
- <body>
- <form id="form1" runat="server">
- <table id="TableID" cellpadding="0" cellspacing="0" border="1" width="400px" >
- <tr>
- <td style="background-color: green; color:white">Name</td>
- <td style="background-color: green; color:white">LastName</td>
- <td style="background-color: green; color:white">Email</td>
- </tr>
- </table>
- </form>
- </body>
- </html>
In the code above I have used the $.parseJSON() method for JSON Data.
- $($.parseJSON(data.d)).each(function (index, value) {
- $("#TableID").append("<tr><td>" + value.Name + "</td><td>" + value.LastName + "</td><td>" + value.Email + "</td></tr>");
- });
When you run the application, it will call the service, fetch data and display in a tabular format as shown in the following figure.