Consuming WCF/ASMX/REST service using JQuery

In this article, I will explain how to consume a WCF / ASMX service using jQuery.  The scope of the article is limited to creating &  consuming different kind of services using jQuery. I have segregated this article into 7 topics based on service consumption.
  1. Calling ASMX Web service using jQuery
  2. Calling WCF service using jQuery and retrieving data in JSON Format
  3. Calling WCF service using jQuery and retrieving data in XML Format
  4. Calling WCF service using jQuery and retrieving data in JSON Format (pass multiple input parameters) & ( Get multiple objects as output using DataContract)
  5. Calling WCF service using jQuery[ Get Method] and retrieving data in JSON Format
  6. Calling REST based WCF service using jQuery
  7. Streaming an image through WCF and request it through HTTP GET verb.
If you have never heard about jQuery or WCF or JSON, please learn it 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 the 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 XMLHttpRequest to the server. In the below code section I have explained the key value pair attributes to be passed by marking comments on the right side of the attribute.
  1. <script type="text/javascript" language="javascript" src="script/jQuery-1.3.2.min.js" "></script>  
  2.   
  3. <script type="text/javascript">  
  4.   
  5.    var varType;  
  6.    var varUrl;  
  7.    var varData;  
  8.    var varContentType;  
  9.    var varDataType;  
  10.    var varProcessData;   
  11.   
  12.    function CallService()   
  13.    {  
  14.            $.ajax({  
  15.                type                : varType, //GET or POST or PUT or DELETE verb  
  16.                url                   : varUrl, // Location of the service  
  17.                data                : varData, //Data sent to server  
  18.                contentType    : varContentType, // content type sent to server  
  19.                dataType         : varDataType, //Expected data format from server  
  20.                processdata    : varProcessData, //True or False  
  21.                success            : function(msg) {//On Successfull service call  
  22.                ServiceSucceeded(msg);                      
  23.                },  
  24.                error: ServiceFailed// When Service call fails  
  25.            });  
  26.    }  
  27. lt;/script>  
I have made the above method generic to use it for all different type of services which we are going to discuss.
 
Business Logic
 
Business logic for below demonstrated service is quite simple, we store Country and Province details in a Name Value collection, When a request supplies the country name it returns the provinces associated with it.
  1. public class CountryProvinceBL  
  2. {  
  3.     NameValueCollection nvProvince = null;  
  4.     public CountryProvinceBL()  
  5.     {  
  6.         nvProvince = new NameValueCollection();  
  7.         nvProvince.Add("usa""Massachusetts");  
  8.         nvProvince.Add("usa""California");  
  9.         nvProvince.Add("india""Tamil Nadu");  
  10.         nvProvince.Add("india""Karnataka");  
  11.     }  
  12.       
  13.     public string[] GetProvince(string Country)  
  14.     {  return nvProvince.GetValues(Country).ToArray();}  
  15.   
  16. }  

1. Calling ASMX Web service using jQuery

 
Step 1
 
Create web service and add the below code
  1. [WebService(Namespace = "http://tempuri.org/")]  
  2. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  3. // Below line allows the web service to be called through HTTP protocol.   
  4. [System.Web.Script.Services.ScriptService]  
  5. public class CountryProvinceWebService : System.Web.Services.WebService  
  6. {  
  7.   
  8.     [WebMethod]  
  9.    //Business Logic returns the provinces for the supplied country  
  10.     public string[] GetProvince(string Country)   
  11.     {  return new CountryProvinceBL().GetProvince(Country); }      
  12. }  
Step 2
 
Invoke the below method on button click
  1. function CountryProvinceWebService() {    
  2.     varType              = "POST";             
  3.     varUrl                 = "service/CountryProvinceWebService.asmx/GetProvince";     
  4.     //Pass country from drop down ddlCountry'    
  5.     varData               = '{"Country": "' + $('#ddlCountry').val() + '"}';    
  6.     varContentType  = "application/json; charset=utf-8";    
  7.     varDataType       = "json";varProcessData = true; CallService();    
  8. }  
Step 3
 
On Success  "ServiceSucceeded" will be called and it will populate the provinces dropdown with the values sent by the server.
  1. function ServiceSucceeded(result) {    
  2.     var ProvinceDDL = document.getElementById("ddlProvince");    
  3.     for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }    
  4.     var resultObject = result.d; // Constructed object name will be object.d //Button     
  5.     for (i = 0; i < resultObject.length; i++) {    
  6.             var opt = document.createElement("option"); opt.text = resultObject[i];    
  7.             ProvinceDDL.options.add(opt)    
  8.         }    
  9. }  

2. Calling WCF service using jQuery and retrieving data in JSON Format

 
Step 1
 
Define  the Contracts  in the interface ICountryProvinceWCFService
  1. [ServiceContract]  
  2. public interface ICountryProvinceWCFService  
  3. {  
  4.     [OperationContract]  
  5.     [WebInvoke(Method = "POST",BodyStyle=WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]      
  6.     string[] GetProvince(string Country);  
  7. }  
Implement the contract in class CountryProvinceWCFService
  1. public class CountryProvinceWCFService : ICountryProvinceWCFService  
  2. {     
  3.   // Call Business Logic to get provinces  
  4.     public string[] GetProvince(string Country)  
  5.     {return new CountryProvinceBL().GetProvince(Country); }  
  6. }  
Step 2
 
Define the configuration in web.config
  • <serviceMetadata httpGetEnabled="true" > enables the user to view the metadata through web browser and generate WSDL  file
  • setting includeExceptionDetailInFaults = "true" allows the WCF service throw original error, it will be useful while debugging the application.
  • Adding  <webHttp/> to endpoint behavior & webHttpBinding to binding enables the web programming model for WCF and allows the service to be accessible through web protocols.
  • Define contract and  name of the service
Figure 1: Web.config
  1. <system.serviceModel>  
  2.    <behaviors>  
  3.        <serviceBehaviors>  
  4.           <behavior name="CountryProvinceBehavior">  
  5.               <serviceMetadata httpGetEnabled="true" />  
  6.               <serviceDebug includeExceptionDetailInFaults="true" />  
  7.          </behavior>  
  8.       </serviceBehaviors>  
  9.       <endpointBehaviors>  
  10.           <behavior name="CountryProvinceBehavior">  
  11.              <webHttp/>          
  12.            </behavior>  
  13.        </endpointBehaviors>   
  14.    </behaviors>  
  15.    <services>  
  16.         <service behaviorConfiguration="CountryProvinceBehavior" name="CountryProvinceWCFService">  
  17.                <endpoint address="" binding="webHttpBinding" contract="ICountryProvinceWCFService" behaviorConfiguration="CountryProvinceBehavior"/>       
  18.         </service>  
  19.    </services>  
  20. lt;/system.serviceModel>  
Step 3

Invoke the WCF service on the button click event
  1. function CountryProvinceWCFJSON() {  
  2.     varType              = "POST";  
  3.     varUrl                 = "service/CountryProvinceWCFService.svc/GetProvince";  
  4.     varData              = '{"Country": "' + $('#ddlCountry').val() + '"}';  
  5.     varContentType = "application/json; charset=utf-8";  
  6.     varDataType      = "json"; varProcessData = true; CallService();  
  7. }  
On successful service invocation  "ServiceSucceeded" will be called and the province value will get added to province drop down.
  1. function ServiceSucceeded(result) {/  
  2.     var ProvinceDDL = document.getElementById("ddlProvince");  
  3.     for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }  
  4.             // Constructed object name will be object.[ServiceName]Result // Button 2 & 3  
  5.            var resultObject = result.GetProvinceResult;  
  6.         for (i = 0; i < resultObject.length; i++) {  
  7.             var opt = document.createElement("option"); opt.text = resultObject[i];  
  8.             ProvinceDDL.options.add(opt)  
  9.         }         
  10. }  

3. Calling WCF service using jQuery and retrieving data in XML Format

Step 1
 
In operation contract set ResponseFormat to XML.
  1. [OperationContract]  
  2. [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped,ResponseFormat = WebMessageFormat.Xml)]  
  3. string[] GetProvinceXML(string Country);  
Then implement the service
  1. public string[] GetProvinceXML(string Country)  
  2. {  
  3.     return new CountryProvinceBL().GetProvince(Country);   
  4. }  
Use the web.config, defined in Figure 1.
 
Step 2
 
Invoke the WCF service on the button click event, Make sure you set the expected data type as XML
  1. function CountryProvinceWCFXML() {    
  2.     varType              = "POST";    
  3.     varUrl                 = "service/CountryProvinceWCFService.svc/GetProvinceXML";    
  4.     varData              = '{"Country": "' + $('#ddlCountry').val() + '"}';    
  5.     varContentType = "application/json; charset=utf-8";     
  6.     varDataType      = "xml";  varProcessData = true; CallService();    
  7. }  
Step 3
 
On successful service invocation "ServiceSucceeded" will be called and the province value will get added to province drop down.
  1. function ServiceSucceeded(result) {    
  2.     var ProvinceDDL = document.getElementById("ddlProvince");    
  3.     for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }    
  4.   //Below jQuery code will loop through the XML result set    
  5.     $(result).find("GetProvinceXMLResult").children().each(function() {    
  6.         var opt = document.createElement("option"); opt.text = $(this).text();    
  7.         ProvinceDDL.options.add(opt)    
  8.     });              
  9. }  

4. Calling WCF service using jQuery and retrieving data in JSON Format

 
In this example Country and Browser type will be passed as input parameter to the WCF service in JSON format, Upon receiving the values the service will send back provinces for the passed country and some comments for the browser information.
 
Step 1
 
Define Data contract and service contact  for the service
  1. [DataContract]  
  2. public class CustomData  
  3. {  
  4.     [DataMember]  
  5.     public String BrowserInfo;  
  6.     [DataMember]  
  7.     public String[] ProvinceInfo;  
  8. }  
  9.   
  10.   [OperationContract]  
  11.     [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]  
  12.     CustomData GetProvinceAndBrowser(string Country, string Browser);  
And implement the contract in your service call
  1. public CustomData GetProvinceAndBrowser(string Country, string Browser)  
  2. {  
  3.     CustomData customData = new CustomData();  
  4.     customData.ProvinceInfo = new CountryProvinceBL().GetProvince(Country);  
  5.     if (Browser == "ie")  
  6.         customData.BrowserInfo = " Did you learn to program IE 8.0";  
  7.     else if (Browser == "firefox")  
  8.         customData.BrowserInfo = " Mozilla rocks, try Firebug & Fiddler addon's";  
  9.     else  
  10.         customData.BrowserInfo = " I did not test in this browser";  
  11.     return customData;  
  12. }  
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
  1.     function CountryProvinceWCFJSONMulti() {    
  2.         var browser = "";    
  3.         if (jQuery.browser.mozilla == true) browser="firefox"    
  4.         else if(jQuery.browser.msie == true) browser = "ie"    
  5.         varType                = "POST";    
  6.         varUrl                   = "service/CountryProvinceWCFService.svc/GetProvinceAndBrowser";    
  7.         //We are passing multiple paramers to the service in json format {"Country" : "india", "Browser":"ie"}    
  8.         varData                = '{"Country": "' + $('#ddlCountry').val() + '","Browser": "' + browser + '"}';    
  9.         varContentType   = "application/json; charset=utf-8";    
  10.         varDataType        = "json";varProcessData = true; CallService();    
  11. }   
Step 4
 
On successful service invocation  "ServiceSucceeded" will be called and the province value will get added to province drop down.
  1. function ServiceSucceeded(result) {    
  2.                   var ProvinceDDL = document.getElementById("ddlProvince");    
  3.                   for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }                       
  4.                  //WCF Service with multiple output paramaetrs //First object     
  5.                   var resultObject = result.GetProvinceAndBrowserResult.ProvinceInfo;    
  6.                   for (i = 0; i < resultObject.length; i++) {    
  7.                       var opt = document.createElement("option"); opt.text = resultObject[i];    
  8.                       ProvinceDDL.options.add(opt)    
  9.                   }    
  10.                   //Second object sent in JSON format    
  11.                   $("#divMulti").html(result.GetProvinceAndBrowserResult.BrowserInfo);              
  12.               }   

5. Calling WCF service using jQuery[ Get Method] and retrieving data in JSON Format

 
This time we will use GET Verb instead of POST to retrieve the data through WCF & jQuery
 
Step 1
 
We can use the WebGet attribute instead of WebInvoke to perform the operation,
  1. [OperationContract]  
  2. [WebGet(ResponseFormat=WebMessageFormat.Json)]  
  3. string[] GetProvinceGET(string Country);  
Implement the contract
  1. public string[] GetProvinceGET(string Country)  
  2. {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 below method
  1. function CountryProvinceWCFJSONGet() {    
  2.     varType                 = "GET";    
  3.     varUrl                    = "service/CountryProvinceWCFService.svc/GetProvinceGET?Country=" +$('#ddlCountry').val();    
  4.     varContentType    = "application/json; charset=utf-8";    
  5.     varDataType = "json";varProcessData = false; CallService();    
  6. }  
On successful service invocation  "ServiceSucceeded" will be called and the province value will get added to province drop down.
  1. function ServiceSucceeded(result) {    
  2.     var ProvinceDDL = document.getElementById("ddlProvince");    
  3.     for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }              
  4.     for (i = 0; i < result.length; i++) {    
  5.         var opt = document.createElement("option"); opt.text = result[i];    
  6.         ProvinceDDL.options.add(opt)    
  7.     }    
  8. }  

6. Calling REST based WCF service using jQuery

 
Step 1
 
Define the URI for REST service in the operation contract and set the BodyStyle to Bare.
  1. [OperationContract]  
  2. [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetProvinceREST/{Country}", BodyStyle=WebMessageBodyStyle.Bare)]  
  3. string[] GetProvinceREST(string Country);  
Implement the contract:
  1. public string[] GetProvinceREST(string Country)  
  2. return new CountryProvinceBL().GetProvince(Country);  }  
Use the web.config defined in Figure 1
 
Step 2
 
While using REST services use GET verb for retrieving data and POST, PUT, DELETE for modifying, adding and deleting information
  1. function CountryProvinceWCFREST() {    
  2.     varType               = "GET";    
  3.     varUrl                  = "service/CountryProvinceWCFService.svc/GetProvinceREST/" + $('#ddlCountry').val();
  4.     varContentType  = "application/json; charset=utf-8";    
  5.     varDataType       = "json"; varProcessData = false; CallService();    
  6. }  
On successful service invocation  "ServiceSucceeded" will be called and the province value will get added to province drop down.
  1. function ServiceSucceeded(result) {    
  2.     var ProvinceDDL = document.getElementById("ddlProvince");    
  3.     for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }              
  4.     for (i = 0; i < result.length; i++) {    
  5.         var opt = document.createElement("option"); opt.text = result[i];    
  6.         ProvinceDDL.options.add(opt)    
  7.     }    
  8. } 

7. Stream an image through WCF and request  it through 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  
  1. [OperationContract]  
  2. [WebInvoke(Method = "GET")]  
  3. Stream GetPicture();  
Implement the contract
  1. public Stream GetPicture()  
  2. {  
  3.     string fileName = Path.Combine(HostingEnvironment.ApplicationPhysicalPath,"vista.jpg");  
  4.     FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);    
  5.    // Set the content type as image/ jpeg  
  6.     System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";  
  7.     return (Stream)fileStream;  
  8. }  
And use the web.config which we defined earlier in this article
 
Step 2
 
On Button  click event set the src attribute of  image element [image1] to  the WCF service
  1. <img src=""  id="image1" width="500" height="400" />  
  2.   
  3. function ShowImage() {// Call the WCF service  
  4.          $("#image1").attr('src','service/CountryProvinceWCFService.svc/GetPicture');  
  5.          
  6.      }  

Conclusion

 
Thanks for reading the article, I know that 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. 


Similar Articles