Click here to Skip to main content
Click here to Skip to main content

Calling a WCF Data Service From jQuery

By , 18 Jul 2010
 

Introduction

I'm working on a lecture about OData which I will present next month (stay tuned for more details in the near future). One of the things that I want to show is how easy and simple it is to consume a WCF Data Service (OData feed) with the jQuery library.
In this post, I'll show you exactly how to do that.

jQuery’s getJSON Method

When you want to load JSON data from the server using a GET HTTP request in jQuery, you will probably use the getJSON method. That method gets as input the server URL, a map of key-value pairs which holds parameters to the server and a callback function to use when the response arrives back to the client and returns the server response in JSON format. This method is the best candidate for consuming WCF Data Services endpoints. If I want to use the getJSON method, I'll do something like the example provided in the getJSON documentation:

$.getJSON('ajax/test.json', function(data) {
  $('.result').html('<p>' + data.foo + '</p>'
    + '<p>' + data.baz[1] + '</p>');
});

How to Consume WCF Data Service with jQuery getJSON Method

When we understand that WCF Data Service is just an HTTP endpoint which returns JSON answer if addressed with JSON request, the road is very clear. If I want to consume the service, all I need to do is create the relevant URI with the WCF Data Service URI conventions and that is it. The following code is an example for that:

$.getJSON("/Services/SchoolService.svc/Courses", null,
    function (data) {
        var sb = new Sys.StringBuilder();
        sb.append("<div>");                                
        $.each(data.d, function (i, item) {
            CreateDivForOneCourse(sb, item)
        });
        sb.append("</div>");
        $('#divResults').html(sb.toString());
    });

What this code is doing is it goes to a WCF Data Service endpoint that is called SchoolService.svc and retrieves the courses entity set it holds. I don’t pass any parameters to the request so the key-value pair is null. In the callback function, I create a StringBuilder object and append to it the response by iterating the data and creating a div for every course. In the end, I put the result as HTML in a div which has an id of divResults.

The All Example Page

<%@ Page Language="C#" AutoEventWireup="true" 
	CodeBehind="ConsumeDataServicejQuery.aspx.cs"
    	Inherits="DataServiceAjaxClient.ConsumeDataService.ConsumeDataServicejQuery" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="../Content/Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="../Content/Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript">
	</script>
    <script type="text/javascript">                
        var ajaxRequest;
 
        $(document).ready(function () {                        
            $('#btnShowCourses').click(function () {
                GetCoursesData();
            });
        });
 
        function GetCoursesData() {
            if (ajaxRequest != null) {
                ajaxRequest.abort();
            }
            ajaxRequest = $.getJSON("/Services/SchoolService.svc/Courses", null,
            function (data) {
                var sb = new Sys.StringBuilder();
                sb.append("<div>");                                
                $.each(data.d, function (i, item) {
                    CreateDivForOneCourse(sb, item)
                });
                sb.append("</div>");
                $('#divResults').html(sb.toString());
            });
        }
 
        function CreateDivForOneCourse(stringBuilder, item) {
            stringBuilder.append("<div><span>");
            stringBuilder.append(item.CourseID);
            stringBuilder.append("</span> <span>");
            stringBuilder.append(item.Title);
            stringBuilder.append("</span></div>");
        }              
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <input type="button" id="btnShowCourses" value="Show Courses" /><br />
        <div id="divResults" />
    </div>
    </form>
</body>
</html>

After running this example, the result looks like:

getJSON result

Summary

Consuming WCF Data Services with jQuery is a very easy task. By using the getJSON method, we create the HTTP GET request to the service and get the returning data in JSON format to
our disposal.


License

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

About the Author

Gil Fink
Architect Sela Group
Israel Israel
Member
Gil Fink is an expert in ASP.NET and Microsoft data platform and serves as a Senior Architect at SELA Group. He is a Microsoft data platform MVP and a certified MCPD Enterprise Application Developer. Gil has worked in the past in variety of positions and projects as a leading developer, team leader, consultant and more. His interests include Entity Framework, Enterprise Library, WCF, LINQ, ADO.NET and many other new technologies from Microsoft.
 

My technical blog: http://www.gilfink.net

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionwindows authenticationmemberpepepaco3 Sep '10 - 7:29 
AnswerRe: windows authenticationmemberGil Fink4 Sep '10 - 19:59 
Hi,
You can try the solution offered here:
http://stackoverflow.com/questions/1002179/how-can-i-pass-windows-authentication-to-webservice-using-jquery[^]

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 18 Jul 2010
Article Copyright 2010 by Gil Fink
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid