Skip to main content

How to consume WCF service using JQuery

  • Create an ASP.NET Web Application (WCF service)
  • Add a new item, aspx page (Default.aspx)
  • You now have an WCF-service with .svc as extension, and that service implements an Interface. It's in the interface we'll set the attributes needed to return JSON
  • Create a class, Student as below. The attributes "DataContract" and "DataMember" must be defined for the class and the properties that would be returned through the WCF service
[DataContract]
public class Student
{
 [DataMember]
 public int StudentId { get; set; }
 [DataMember]
 public string StudentName { get; set; }
 [DataMember]
 public int Marks1 { get; set; }
 [DataMember]
 public int Marks2 { get; set; }
 [DataMember]
 public string EmailAddress { get; set; }
}
  • Now add a reference to System.ServiceModel.Web this is for WebGet Attribute
  • Add the WebGet-attribute as specified below. The BodyStyle Bare means "Both requests and responses are not wrapped" - we really want nothing more than a true JSON-response. The ResponseFormat should of course be "Json".
[ServiceContract]
public interface IService
{
 [OperationContract]
 [WebGet(UriTemplate = "NewUri/?value={value}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
 string GetData(int value);
 [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
 [OperationContract]
 List<Student> GetStudentList();

}
  • In web config, start with changing "wsHttpBinding" to "webHttpBinding" (we are not working with Web Services now), then add the whole section below with our self-named behavior "JsonBehavior". Now add the behaviorConfiguration="JsonBehavior" attribute to the service-tag.
<system.serviceModel>
 <services>
   <service name="Service" behaviorConfiguration="ServiceBehavior">
     <endpoint address="" binding="webHttpBinding" behaviorConfiguration="JsonBehavior" bindingConfiguration="" contract="IService"/>
   </service>
 </services>
 <behaviors>
   <endpointBehaviors>

     <behavior name="JsonBehavior">
       <webHttp />
     </behavior>
   </endpointBehaviors>
   <serviceBehaviors>
     <behavior name="ServiceBehavior">
       <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
       <serviceMetadata httpGetEnabled="true"/>
       <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
       <serviceDebug includeExceptionDetailInFaults="false"/>
     </behavior>
   </serviceBehaviors>
 </behaviors>
</system.serviceModel>
</configuration>
Here is the complete source code IService.cs
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;


[ServiceContract]
public interface IService
{
  [OperationContract]
  [WebGet(UriTemplate = "NewUri/?value={value}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
  string GetData(int value);
  [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
  [OperationContract]
  List<Student> GetStudentList();

}
[DataContract]
public class Student
{
  [DataMember]
  public int StudentId { get; set; }
  [DataMember]
  public string StudentName { get; set; }
  [DataMember]
  public int Marks1 { get; set; }
  [DataMember]
  public int Marks2 { get; set; }
  [DataMember]
  public string EmailAddress { get; set; }
}

Service.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: If you change the class name "Service" here, you must also update the reference to "Service" in Web.config and in the associated .svc file.
public class Service : IService
{
  public string GetData(int value)
  {
      return string.Format("You entered: {0}", value);
  }
  /// <summary>
  /// Return List of student.
  /// </summary>
  /// <returns></returns>
  public List<Student> GetStudentList()
  {

      List<Student> students = new List<Student>()
         {  new Student{StudentId=1,StudentName="S#001",Marks1=10,Marks2=20,EmailAddress="student1@st.com"},
             new Student{StudentId=2,StudentName="S#002",Marks1=9,Marks2=30, EmailAddress="student2@st.com"},
             new Student{StudentId=3,StudentName="S#003",Marks1=11,Marks2=20,EmailAddress="student3@st.com"},
             new Student{StudentId=4,StudentName="S#004",Marks1=20,Marks2=30,EmailAddress="student4@st.com"},
             new Student{StudentId=5,StudentName="S#005",Marks1=9,Marks2=40,EmailAddress="student5@st.com"},
             new Student{StudentId=6,StudentName="S#006",Marks1=30,Marks2=50,EmailAddress="student6@st.com"},
         };
      return students;

  }
}
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.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 runat="server">
  <title></title>

  <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

  <script type="text/javascript">
      $().ready(function() {
          $("#btnStudent").click(function() {
              $.getJSON("Service.svc/GetStudentList", function(data) {
                  BuildTable(data);
              });
          });

          $("#myButt").click(function() {
              var num = $("#name").val();
              $.getJSON("Service.svc/NewUri", { value: num }, function(data) {
                  alert(data);
              });
          });
      });
      function BuildTable(data) {
          var table = '<table><thead><tr><th>StudentID</th><th>StudentName</th><th>Marks1</th></thead><tbody>';

          $.each(data, function(i, student) {
              var row = '<tr>';
              row += '<td>' + student.StudentId + '</td>';
              row += '<td>' + student.StudentName + '</td>';
              row += '<td>' + student.Marks1 + '</td>';
              row += '</tr>';
              table += row;
          });
          table += '</tbody></table>';
          $('#Container').html(table);
      }
  </script>

</head>
<body>
  <form id="form1" runat="server">
  <div>
      <input type="button" value="Get values from server" id="myButt" />
      <input type="button" value="GetStudentList" id="btnStudent" />
      <p>
          <input type="text" id="name" value="1" /><br />
      </p>
  </div>
  <div id="Container">
  </div>
  </form>
</body>
</html>
Service.svc
<%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>

Comments

  1. Thanks buddy...

    ReplyDelete
  2. Muchasgracias, excelente, gracias a tí pude verificar donde estaba en el error.

    Saludos, que tengas buen dia!!!

    ReplyDelete
  3. Thank You Very Much :)

    ReplyDelete

Post a Comment

Popular posts from this blog