Tuesday, October 2, 2012

Restful WCF service with Jquery

This is my first post about how to call a WCF service with jquery.

This post will describe how do you pass your parameters through your jquery ajax method to a WCF service.

First we will start with WCF Service....(Restful Service)

Step 1. Create a WCF Service Application


Step 2.  Open your IService1.cs File and put the below code there...

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

namespace RestFullService
{
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebInvoke(Method = "PUT", UriTemplate = "/Test", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        string Test(Parameters param);
    }
    [DataContract]
    public class Parameters
    {
        [DataMember]
        public string Value { get; set; }
    }

}

Step 3. Now open your Service1.svc.cs File and paste the below code there...

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

namespace RestFullService
{
    public class Service1 : IService1
    {
        public string Test(Parameters param)
        {
            JavaScriptSerializer jSerializer = new JavaScriptSerializer();
            dynamic oParam = jSerializer.Deserialize<dynamic>(param.Value);
            Employee emp = new Employee();
            DataTable dtEmployee = emp.GetEmployee(oParam["id"], oParam["name"]);
            //Here is the code to Serialize the Datatable
            //This will serialize you databale as a List Array.
            List<Dictionary<string, object>> lstSerializeList = new List<Dictionary<string, object>>();
            Array.ForEach(dtEmployee.Select(), row =>
            {
               Dictionary<stringobject> Dictionary = new Dictionary<stringobject>();
                foreach (DataColumn col in dtEmployee.Columns)
                    Dictionary.Add(col.ColumnName, row[col]);
                lstSerializeList.Add(Dictionary);
            });

            return jSerializer.Serialize(lstSerializeList);

        }
    }
    public class Employee
    {
        //Call your Database as your way to get the Data
        // I am using DataTable as a return type... 
        public DataTable GetEmployee(string id,string Name)
        {
            //Do your Code here
            return new DataTable();
        }
    }
}

Step 4. We are done with WCF. Now we will call Javascript to call this service and pass parameters. For this we will add a empty web application which will consume this service and pass parameters to it. WCF Service will return a JSON string to jquery ajax method.

You will need some jquery js files.

jquery.js
jquery.ui.core.js
jquery-1.7.2.js

<script language=javascript>
    function passParameterToService() {
        //By this way you can declare your parameters...
        var data= {};
        data.id = "1";
        data.Name = "EmployeeName";

        var dataAsString = data;
        if ($.type(data) === "object")
       {
            dataAsString = JSON.stringify(data);
       }
       else
       {
          dataAsString = data;
       }

       var dataString = { Value: dataAsString };
       dataString = { param: dataString };
        // This Method will call your ajax service with the parameters
        CallService(dataString );

    }
function CallService(data)
{
    $.ajax({
        type: "PUT",
        url: "http://localhost:<PortNumber>/EndPointName/Test", 
        data: data,
        contentType: "json", 
        dataType: "application/json; charset=utf-8",
        success: function (msg) {
            //On Successful service call
            sucessFunction(msg);
        },
        error: ServiceFailed// When Service call fails
    });
}

function ServiceFailed(result)
{
  alert('Service call failed: \n Status : ' + result.status + ' Status Text : ' + result.statusText);
}
function sucessFunction(msg) {
     // Here you will receive your JSON string.......
}
</script>









No comments:

Post a Comment