Display WCF Data Service Into HTML Page

Introduction

This article explains the basic way to consume data from WCF. This data might be from a database or any business logic. But the important this is how to consume the data into a HTML file.  

wcf

In this image, we can understand that JSON helps to get the WCF services and jQuery will help JSON to display objects and we can call anything into HTML from jQuery.

The following is the basic procedure for consuming WCF services into a HTML page:

  • Create a WCF Service
  • Consume into jQuery
  • Display into HTML page

Create a WCF Service

Add a WCF Project as in the following:

AddWCFProject

Interface code

  1. [ServiceContract]  
  2.     public interface IService1  
  3.     {  
  4.         [OperationContract]  
  5.         [WebGet(RequestFormat = WebMessageFormat.Json,  
  6.             ResponseFormat = WebMessageFormat.Json,  
  7.             UriTemplate = "/GetData/")]  
  8.         string GetData();          
  9.     }  

Class code 

  1. public class Service1 : IService1  
  2. {  
  3.   public string GetData()  
  4.   {  
  5.     return "Hello World";  
  6.   }  
    }  
Note : Add the serviceModel.web namespace to your project. Click on Add Reference and add the assemblies.

reference1

reference2

The WebGetAttribute is applied to a service operation in addition to the operation in addition to the OperationalContractAttribue and associate the operation with UriTemplates as well as the HTTP GET verb. The association with HTTP Get verb means that the operation is used to retrieve information from the service.

Example  
  1. [OperationContract]  
  2.   
  3.        [WebGet(ResponseFormat = WebMessageFormat.Json)]  
  4.        long Mod(long x, long y);  

Set the behaviors in the web.config file as in the following:

  1. <behaviors>  
  2.            <serviceBehaviors>  
  3.            <behavior name="ServiceBehaviour">  
  4.            <serviceMetadata httpGetEnabled="true" />  
  5.            <serviceDebug includeExceptionDetailInFaults="false" />  
  6. </behavior>  

Add the endpoint address as in the following:

  1. <services>  
  2.       <service name="WcfService1.Service1">  
  3.         <endpoint address="" binding="webHttpBinding" behaviorConfiguration="web"  contract="WcfService1.IService1" bindingConfiguration="b_WebHttpBinding"></endpoint>  
  4.       </service>  
  5. </services>  

Add the binding as in the following:

  1. <bindings>  
  2.      <webHttpBinding>  
  3.        <binding name="b_WebHttpBinding" closeTimeout="00:01:00"  
  4.            openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"  
  5.            allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"  
  6.            maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" transferMode="Buffered"  
  7.            useDefaultWebProxy="true" crossDomainScriptAccessEnabled="true">  
  8.          <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647"  
  9.              maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />  
  10.          <security mode="None">  
  11.            <transport clientCredentialType="None" proxyCredentialType="None"  
  12.                realm="" />  
  13.          </security>  
  14.        </binding>  
  15.      </webHttpBinding>  
  16.    </bindings>  

Run the project , you will see the output screen in your browser like this:

output1

When we call the method name in the URL we are able to see the output in the browser, as in the following image. 

output2

Consume into jQuery

jQuery consumes WCF Services, the ajax() method does the asynchronous HTTP (AJAX) request.

Syntax

$.ajax({
              type: ,
              content type : ,
              url : ,
             data : ,
             async : ,
             success :,
             error :
          });

These are the few parameters, described in the following:

  1. $.ajax({  
  2.            type: "GET",  
  3.            url: "Service1.svc/GetData",  
  4.            contentType: "application/json; charset=utf-8",  
  5.            dataType: "json",  
  6.            success: function (msg) {  
  7.            alert(msg);  
  8.            },  
  9.            error: function (msg){  
  10.                alert("error")  
  11.             }  
  12.        });  

Type : GET / POST.
ContentType : when we send data to the server, we use the contentType "application/x-www-form-undercoded".
URL : (wcf services) address.
Data : defines the data to be sent to the server.
Success : A callback function that executes if the function is successful.
Error : when a problem or exception occurrs the error part will run.
HTML page

  1. <html>  
  2. <head>  
  3.     <title></title>  
  4.     <script src="Scripts/jquery-2.1.1.min.js"></script>  
  5. </head>  
  6. <body>  
  7.     <script>  
  8.         function show() {  
  9.                 $.ajax({  
  10.                 type: "GET",  
  11.                 url: "Service1.svc/GetData",  
  12.                 contentType: "application/json; charset=utf-8",  
  13.                 dataType: "json",  
  14.                 success: function (msg) {  
  15.                     alert(msg);  
  16.                 },  
  17.                 error: function (msg){  
  18.                     alert("error")  
  19.                 }  
  20.             });  
  21.         }  
  22.     </script>  
  23.     <button onclick="show()">click</button>  
  24. </body>  
  25. </html>  

In this code above, there is a button and in the button's click event we call the jQuery function. 

finalout1

finalout2

In this figure we are able to see the output "hello world" as we saw in the WCF output screen on the browser.

Summary

In this article we learned the simple procedure for consuming a WCF service into a HTML file. We also learned the basic syntax for a WCF Service and jQuery while consuming into the HTML page. Thanks for reading this article.


Similar Articles