Follow by Email

Thursday, May 23, 2013

call a asp.net wcf service using jquery | Ajax Json Call to WCF using Jquery

Hi in post i will show how to call a asp.net wcf service using jquery.

1. Take a new website empty template add aspx page and wcf service page.

2. Go to App_Code --> IService.cs to define the method signature.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
    string GetDate(string Date);    
}


3. Go to App_Code --> Service.cs to write the implementation for the declared method signature.

using System;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Web.Script.Serialization;
using System.ServiceModel.Activation;

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
    public string GetDate(string Date)
    {
        return "'Hello World' Todays Date is : " + Date.ToString();
    }
}


4. Now in the Web.config file i will define the address, binding, contract and service behaviours for the WCF Service

Under the configuration tag add this:

<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
        <endpointBehaviors>
            <behavior name="ServiceAspNetAjaxBehavior">
                <enableWebScript />
            </behavior>
        </endpointBehaviors>
</behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <services>
<service behaviorConfiguration="ServiceBehavior" name="Service">
<endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="ServiceAspNetAjaxBehavior">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel> 

5. Now writing the jquery ajax code to call the wcf service.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://code.jquery.com/jquery-1.8.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        var d = new Date();

        function CallWCF() {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: '<%=ResolveUrl("~/Service.svc/GetDate") %>',
                data: '{"Date": "' + d.toDateString() + '"}',
                processData: true,
                dataType: "json",
                success: ServiceSucceeded,
                error: ServiceFailed
            });
        }

        function ServiceFailed(output) {
            Log('Service call failed: ' + output.status + ' ' + output.statusText);
        }

        function ServiceSucceeded(output) {
            var outputValue = output.d;
            Log("Service call Success: <br/> " + outputValue);
        }

        function Log(displayValueFromService) {
            $("#DisplayOutput").append('<br/>' + displayValueFromService);
        }
    </script>
</head>
<body>
    <input id="Button1" type="button" value="Call WCF Service" onclick="CallWCF();" />
    <div id="DisplayOutput">
    </div>
</body>
</html>


6. Result: