Click here to Skip to main content
15,879,535 members
Articles / Web Development / ASP.NET

Consuming a WCF / ASMX / REST Service using jQuery

Rate me:
Please Sign up or sign in to vote.
4.81/5 (39 votes)
20 Feb 2010CPOL5 min read 206.7K   7.7K   178   28
This step by step tutorial demonstrates how to consume a WCF, ASMX, and REST Service from an application using jQuery.

Introduction

In this article, I will explain how to consume a WCF / ASMX service using jQuery. The scope of the article is limited to creating and consuming different kinds of services using jQuery. I have segregated this article into seven topics based on the service consumption.

  1. Calling an ASMX Web Service using jQuery
  2. Calling a WCF Service using jQuery and retrieving data in JSON format
  3. Calling a WCF Service using jQuery and retrieving data in XML format
  4. Calling a WCF Service using jQuery and retrieving data in JSON format (pass multiple input parameters) and (get multiple objects as output using a DataContract)
  5. Calling a WCF Service using jQuery [GET method] and retrieving data in JSON format
  6. Calling a REST based WCF Service using jQuery
  7. Streaming an image through WCF and requesting it through the HTTP GET verb

If you have never heard about jQuery or WCF or JSON, please learn about them before dwelling into this article. The scope is limited to service creation and consumption.

I used Visual Web Developer 2008 to develop this sample. Additional tools used: Firebug and HttpAnalyzer.

3_project_structure.jpg

In the below example, I have used jQuery version 1.3.2. You can download the same from http://jQuery.com/. This article demonstrates how our jQuery based browser app will retrieve the provinces for a supplied country. All the services are hosted in the same web application. Please download the source code to experiment with the sample by yourself.

1Screen.jpg

For calling the service, we need to use the .ajax method of jQuery which makes an XMLHttpRequest to the server. In the code section below, I have explained the key value pair attributes to be passed by marking the comments on the right side of the attribute.

JavaScript
<script type="text/javascript" language="javascript" 
   src="script/jQuery-1.3.2.min.js" "></script>

     <script type="text/javascript">

        var varType;
        var varUrl;
        var varData;
        var varContentType;
        var varDataType;
        var varProcessData;

        function CallService()
        {
                $.ajax({
                    type          : varType, //GET or POST or PUT or DELETE verb
                    url           : varUrl, // Location of the service
                    data          : varData, //Data sent to server
                    contentType   : varContentType, // content type sent to server
                    dataType      : varDataType, //Expected data format from server
                    processdata   : varProcessData, //True or False
                    success       : function(msg) {//On Successfull service call
                    ServiceSucceeded(msg);                    
                    },
                    error: ServiceFailed// When Service call fails
                });
        }
    </script>

I have made the above method generic to use it for all different types of services which we are going to discuss.

Business Logic

The business logic for the service demonstrated below is quite simple. We store the Country and Province details in a Name Value collection. When a request supplies the country name, we return the provinces associated with it.

C#
public class CountryProvinceBL
{
    NameValueCollection nvProvince = null;
    public CountryProvinceBL()
    {
        nvProvince = new NameValueCollection();
        nvProvince.Add("usa", "Massachusetts");
        nvProvince.Add("usa", "California");
        nvProvince.Add("india", "Tamil Nadu");
        nvProvince.Add("india", "Karnataka");
    }
    
    public string[] GetProvince(string Country)
    {  return nvProvince.GetValues(Country).ToArray();}

}

1. Calling an ASMX Web Service Using jQuery

Step 1

Create a Web Service and add the code below:

C#
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// Below line allows the web service to be called through HTTP protocol.
[System.Web.Script.Services.ScriptService]
public class CountryProvinceWebService : System.Web.Services.WebService
{

    [WebMethod]
   //Business Logic returns the provinces for the supplied country
    public string[] GetProvince(string Country)
    {  return new CountryProvinceBL().GetProvince(Country); }    
}

Step 2

Invoke the method below on button click:

JavaScript
function CountryProvinceWebService() {
    varType              = "POST";         
    varUrl                 = "service/CountryProvinceWebService.asmx/GetProvince";
    //Pass country from drop down ddlCountry'
    varData               = '{"Country": "' + $('#ddlCountry').val() + '"}';
    varContentType  = "application/json; charset=utf-8";
    varDataType       = "json";varProcessData = true; CallService();
}

Step 3

On success, ServiceSucceeded will be called, and it will populate the provinces dropdown with the values sent by the server.

JavaScript
function ServiceSucceeded(result) {
    var ProvinceDDL = document.getElementById("ddlProvince");
    for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
    var resultObject = result.d; // Constructed object name will be object.d //Button
    for (i = 0; i < resultObject.length; i++) {
        var opt = document.createElement("option"); opt.text = resultObject[i];
        ProvinceDDL.options.add(opt)
    }
}

2. Calling a WCF Service using jQuery and retrieving data in JSON format

Step 1

Define the Contracts in the interface ICountryProvinceWCFService.

C#
[ServiceContract]
public interface ICountryProvinceWCFService
{
    [OperationContract]
    [WebInvoke(Method = "POST", 
      BodyStyle=WebMessageBodyStyle.Wrapped, 
      ResponseFormat = WebMessageFormat.Json)]    
    string[] GetProvince(string Country);
}

Implement the contract in the class CountryProvinceWCFService.

JavaScript
public class CountryProvinceWCFService : ICountryProvinceWCFService
{   
    // Call Business Logic to get provinces
    public string[] GetProvince(string Country)
    {return new CountryProvinceBL().GetProvince(Country); }
}

Step 2

Define the configuration in web.config:

  1. <servicemetadata httpgetenabled="true"> enables the user to view the metadata through the web browser and generate the WSDL file.
  2. Setting includeExceptionDetailInFaults = "true" allows the WCF service to throw the original error; it will be useful while debugging the application.
  3. Adding <webhttp> to the endpoint behaviour and webHttpBinding to binding enables the web programming model for WCF, and allows the service to be accessible through web protocols.
  4. Define the contract and the name of the service.
Figure 1: Web.config
XML
<system.serviceModel>
    <behaviors>
        <serviceBehaviors>
           <behavior name="CountryProvinceBehavior">
               <serviceMetadata httpGetEnabled="true" />
               <serviceDebug includeExceptionDetailInFaults="true" />
          </behavior>
       </serviceBehaviors>
       <endpointBehaviors>
           <behavior name="CountryProvinceBehavior">
              <webHttp/>        
            </behavior>
        </endpointBehaviors> 
    </behaviors>
    <services>
         <service behaviorConfiguration="CountryProvinceBehavior" 
                  name="CountryProvinceWCFService">
                <endpoint address="" binding="webHttpBinding" 
                   contract="ICountryProvinceWCFService" 
                   behaviorConfiguration="CountryProvinceBehavior"/>     
         </service>
    </services>
</system.serviceModel>

Step 3

Invoke the WCF service on the button click event:

JavaScript
function CountryProvinceWCFJSON() {
    varType              = "POST";
    varUrl                 = "service/CountryProvinceWCFService.svc/GetProvince";
    varData              = '{"Country": "' + $('#ddlCountry').val() + '"}';
    varContentType = "application/json; charset=utf-8";
    varDataType      = "json"; varProcessData = true; CallService();
}

On successful service invocation, ServiceSucceeded will be called and the province values will get added to the province drop down.

JavaScript
function ServiceSucceeded(result) {/
   var ProvinceDDL = document.getElementById("ddlProvince");
   for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
   // Constructed object name will be object.[ServiceName]Result // Button 2 & 3
   var resultObject = result.GetProvinceResult;
   for (i = 0; i < resultObject.length; i++) {
       var opt = document.createElement("option"); 
       opt.text = resultObject[i];
       ProvinceDDL.options.add(opt)
   }       
}

3. Calling a WCF Service using jQuery and retrieving data in XML format

Step 1

In the operation contract, set ResponseFormat to XML.

C#
[OperationContract]
[WebInvoke(Method = "POST", 
  BodyStyle = WebMessageBodyStyle.Wrapped, 
  ResponseFormat = WebMessageFormat.Xml)]
string[] GetProvinceXML(string Country);

Then, implement the service:

C#
public string[] GetProvinceXML(string Country)
{  return new CountryProvinceBL().GetProvince(Country); }

Step 2

Invoke the WCF service on the button click event. Make sure you set the expected data type as XML.

JavaScript
function CountryProvinceWCFXML() {
    varType              = "POST";
    varUrl                 = "service/CountryProvinceWCFService.svc/GetProvinceXML";
    varData              = '{"Country": "' + $('#ddlCountry').val() + '"}';
    varContentType = "application/json; charset=utf-8";
    varDataType      = "xml";  varProcessData = true; CallService();
}

Use the web.config defined in Figure 1.

Step 3

On successful service invocation, ServiceSucceeded will be called and the province values will get added to the province drop down.

JavaScript
function ServiceSucceeded(result) {
    var ProvinceDDL = document.getElementById("ddlProvince");
    for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
    //Below jQuery code will loop through the XML result set
    $(result).find("GetProvinceXMLResult").children().each(function() {
      var opt = document.createElement("option"); opt.text = $(this).text();
      ProvinceDDL.options.add(opt)
    });          
}

4. Calling a WCF Service using jQuery and retrieving data in JSON format (pass multiple input parameters and get multiple objects as output using a DataContract)

In this example, the Country and Browser type will be passed as input parameters to the WCF Service in JSON format. Upon receiving the values, the service will send back the provinces for the passed country and some comments for the browser information.

Step 1

Define the Data Contract and the Service Contract for the service:

C#
[DataContract]
public class CustomData
{
    [DataMember]
    public String BrowserInfo;
    [DataMember]
    public String[] ProvinceInfo;
}

[OperationContract]
[WebInvoke(Method = "POST", 
  BodyStyle = WebMessageBodyStyle.Wrapped, 
  ResponseFormat = WebMessageFormat.Json)]
CustomData GetProvinceAndBrowser(string Country, string Browser);

And implement the contract in your service call:

C#
public CustomData GetProvinceAndBrowser(string Country, string Browser)
{
    CustomData customData = new CustomData();
    customData.ProvinceInfo = new CountryProvinceBL().GetProvince(Country);
    if (Browser == "ie")
        customData.BrowserInfo = " Did you learn to program IE 8.0";
    else if (Browser == "firefox")
        customData.BrowserInfo = " Mozilla rocks, try Firebug & Fiddler addon's";
    else
        customData.BrowserInfo = " I did not test in this browser";
    return customData;
}

Step 2

Use the web.config defined in figure 1.

Step 3

Invoke the WCF service on the button click event. Make sure you set the expected data type as XML.

JavaScript
function CountryProvinceWCFJSONMulti() {
    var browser = "";
    if (jQuery.browser.mozilla == true) browser="firefox"
    else if(jQuery.browser.msie == true) browser = "ie"
    varType   = "POST";
    varUrl    = "service/CountryProvinceWCFService.svc/GetProvinceAndBrowser";
    //We are passing multiple paramers to the service in JSON format
    // {"Country" : "india", "Browser":"ie"}
    varData   = '{"Country": "' + $('#ddlCountry').val() + 
                '","Browser": "' + browser + '"}';
    varContentType   = "application/json; charset=utf-8";
    varDataType      = "json";varProcessData = true; CallService();
}

Step 4

On successful service invocation, ServiceSucceeded will be called and the province values will get added to the province drop down.

JavaScript
function ServiceSucceeded(result) {
    var ProvinceDDL = document.getElementById("ddlProvince");
    for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
    //WCF Service with multiple output paramaetrs //First object
    var resultObject = result.GetProvinceAndBrowserResult.ProvinceInfo;
    for (i = 0; i < resultObject.length; i++) {
        var opt = document.createElement("option"); opt.text = resultObject[i];
        ProvinceDDL.options.add(opt)
    }
    //Second object sent in JSON format
    $("#divMulti").html(result.GetProvinceAndBrowserResult.BrowserInfo);          
}

5. Calling a WCF Service using jQuery [GET method] and retrieving data in JSON format

This time, we will use the GET Verb instead of POST to retrieve the data through WCF and jQuery.

Step 1

We can use the WebGet attribute instead of WebInvoke to perform the operation.

C#
[OperationContract]
[WebGet(ResponseFormat=WebMessageFormat.Json)]
string[] GetProvinceGET(string Country);

Implement the contract:

C#
public string[] GetProvinceGET(string Country)
{return new CountryProvinceBL().GetProvince(Country);}

And use the web.config defined in figure 1.

Step 2

Set the verb to GET instead of POST, and pass the data as a query string. Invoke the WCF Service using the method below.

JavaScript
function CountryProvinceWCFJSONGet() {
    varType    = "GET";
    varUrl     = "service/CountryProvinceWCFService.svc/" + 
                 "GetProvinceGET?Country=" +$('#ddlCountry').val();
    varContentType    = "application/json; charset=utf-8";
    varDataType = "json";varProcessData = false; CallService();
}

On successful service invocation, ServiceSucceeded will be called and the province values will get added to the province drop down.

JavaScript
function ServiceSucceeded(result) {
   var ProvinceDDL = document.getElementById("ddlProvince");
   for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
   for (i = 0; i < result.length; i++) {
       var opt = document.createElement("option"); opt.text = result[i];
       ProvinceDDL.options.add(opt)
   }
}

6. Calling a REST based WCF Service using jQuery

Step 1

Define the URI for the REST service in the operation contract and set the BodyStyle to Bare.

C#
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, 
  UriTemplate = "GetProvinceREST/{Country}", 
  BodyStyle=WebMessageBodyStyle.Bare)]
string[] GetProvinceREST(string Country);

Implement the contract:

C#
public string[] GetProvinceREST(string Country)
{ return new CountryProvinceBL().GetProvince(Country);  }

Use the web.config defined in Figure 1.

Step 2

While using the REST services, use the GET verb for retrieving data, and POST, PUT, DELETE for modifying, adding, and deleting information.

JavaScript
function CountryProvinceWCFREST() {
    varType    = "GET";
    varUrl     = "service/CountryProvinceWCFService.svc/" + 
                 "GetProvinceREST/" + $('#ddlCountry').val();            
    varContentType  = "application/json; charset=utf-8";
    varDataType     = "json"; varProcessData = false; CallService();
}

On successful service invocation, ServiceSucceeded will be called and the province values will get added to the province drop down.

JavaScript
function ServiceSucceeded(result) {
   var ProvinceDDL = document.getElementById("ddlProvince");
   for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }          
   for (i = 0; i < result.length; i++) {
       var opt = document.createElement("option"); opt.text = result[i];
       ProvinceDDL.options.add(opt)
   }
}

7. Stream an image through WCF and request it through the HTTP GET Verb

2_WCF_Image.jpg

Step 1

Define the contract, and set the return type to Stream since we are going to send it in Image/JPEG format.

C#
[OperationContract]
[WebInvoke(Method = "GET")]
Stream GetPicture();

Implement the contract:

C#
public Stream GetPicture()
{
    string fileName = Path.Combine(
      HostingEnvironment.ApplicationPhysicalPath,"vista.jpg");
    FileStream fileStream = 
      new FileStream(fileName, FileMode.Open, FileAccess.Read);  
    // Set the content type as image/ jpeg
    System.ServiceModel.Web.WebOperationContext.
      Current.OutgoingResponse.ContentType = "image/jpeg";
    return (Stream)fileStream;
}

And, use the web.config which we defined earlier in this article

Step 2

On the button click event, set the src attribute of the image element [image1] to the WCF service.

JavaScript
<img src=""  id="image1" width="500" height="400" />
function ShowImage() {// Call the WCF service
    $("#image1").attr('src', 
      'service/CountryProvinceWCFService.svc/GetPicture');
}

Conclusion

Thanks for reading the article. I have not gone into the details of each and every aspect to keep the article shorter. Please download the source code to check the examples yourself. I have validated the example in IE 7 and Firefox 3.5. If you have any suggestions / comments / doubts regarding the article, don't hesitate to post it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United States United States
Developing software since 2000.

Comments and Discussions

 
QuestionWCF Service using JSON/JSONP ??? Pin
kumar thrishool15-Aug-14 0:05
kumar thrishool15-Aug-14 0:05 
Questiongreat post but assumes you have access to the WCF web service Pin
docdaven13-Dec-13 8:58
docdaven13-Dec-13 8:58 
QuestionHow to pass Client Credentials for the WCF Service from script Pin
vjspeaks13-Aug-13 1:31
vjspeaks13-Aug-13 1:31 
AnswerRe: How to pass Client Credentials for the WCF Service from script Pin
Sridhar Subramanian17-Aug-13 5:12
Sridhar Subramanian17-Aug-13 5:12 
GeneralMy vote of 5 Pin
vicoruga2-Aug-13 9:06
vicoruga2-Aug-13 9:06 
GeneralMy vote of 5 Pin
LuisManuelSanchez17-Jun-13 5:05
LuisManuelSanchez17-Jun-13 5:05 
GeneralGreat Article Pin
cbxjones11-Feb-13 11:11
cbxjones11-Feb-13 11:11 
GeneralMy vote of 5 Pin
BeamingJo29-Jan-13 19:58
BeamingJo29-Jan-13 19:58 
Really good article.

Thanks for sharing your knowledge.
QuestionGreat article! / related question Pin
Benrhere27-Feb-12 5:43
Benrhere27-Feb-12 5:43 
QuestionService Call Failed : No Transport 0 Pin
jonelster12-Feb-12 11:37
jonelster12-Feb-12 11:37 
QuestionMany Thankssssss Pin
arinpcssouth30-Sep-11 7:32
arinpcssouth30-Sep-11 7:32 
GeneralGreat Article Pin
Gary Stafford29-Sep-11 16:34
Gary Stafford29-Sep-11 16:34 
GeneralMy vote of 3 Pin
Member 823287813-Sep-11 2:07
Member 823287813-Sep-11 2:07 
QuestionHow to consume this WCF servise in Windows application? Pin
Kunjee11-Aug-11 16:30
Kunjee11-Aug-11 16:30 
AnswerRe: How to consume this WCF servise in Windows application? Pin
Sridhar Subramanian12-Aug-11 1:04
Sridhar Subramanian12-Aug-11 1:04 
Generalnice one,thanks Pin
Layinka17-Feb-11 0:00
professionalLayinka17-Feb-11 0:00 
Generalnice one Pin
Pranay Rana30-Dec-10 17:21
professionalPranay Rana30-Dec-10 17:21 
GeneralGood Work Pin
ShashankSinghThakur16-Oct-10 6:19
ShashankSinghThakur16-Oct-10 6:19 
GeneralBrilliant. Pin
Chris Aylott7-Oct-10 5:52
Chris Aylott7-Oct-10 5:52 
QuestionExcellent Job - Asp.Net 4 / Ado.Net DataServices ? Pin
Paul Chu3-May-10 11:09
Paul Chu3-May-10 11:09 
AnswerRe: Excellent Job - Asp.Net 4 / Ado.Net DataServices ? Pin
Sridhar Subramanian6-May-10 10:32
Sridhar Subramanian6-May-10 10:32 
Generalgood work Pin
Muhammad Shoaib Raja12-Apr-10 20:27
Muhammad Shoaib Raja12-Apr-10 20:27 
GeneralRe: good work Pin
Sridhar Subramanian22-Apr-10 1:08
Sridhar Subramanian22-Apr-10 1:08 
GeneralThe Security of web service or WCF Pin
nicholas_pei21-Feb-10 22:46
nicholas_pei21-Feb-10 22:46 
GeneralRe: The Security of web service or WCF Pin
Sridhar Subramanian25-Feb-10 7:12
Sridhar Subramanian25-Feb-10 7:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.