WCF RIA Services, jQuery, and JSON endpoint – Part 1

Here I will show how to perform a simple load using jQuery and RIA Services.

Pre-requisites:

Server Setup

I start with the server because the namespace and class names affect the jQuery code. To keep things simple (and remove the need for a database and DAL) I will use a POCO DomainService. There is a PocoEntity with a key and data field. It is exposed by the GetPoco method.

PocoEntity.cs

using System.ComponentModel.DataAnnotations;
namespace jQueryDemo.Web
{
    public class PocoEntity
    {
        [Key]
        public string EntityKey { get; set; }
        public string EntityData { get; set; }
    }
}

PocoDomainService.cs

namespace jQueryDemo.Web{    using System.Collections.Generic;    using System.Linq;    using System.ServiceModel.DomainServices.Hosting;    using System.ServiceModel.DomainServices.Server;     [EnableClientAccess()]    public class PocoDomainService : DomainService    {        private static List pocoList;         public PocoDomainService()        {            pocoList = new List();            pocoList.Add(new PocoEntity() { EntityKey = "1", EntityData = "Entity 1 Server Data" });        }         public IQueryable GetPoco()        {            return pocoList.AsQueryable();        }    }}

Client Setup

On the client include the json2 and jquery-1.4.2.js. I prefer to create a separate file for my javascript code.

jQueryDemo.html

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="scripts/json2.js" type="text/javascript" />
    <script src="scripts/jquery-1.4.2.js" type="text/javascript" />
    <script src="scripts/jQueryDemo.js" type="text/javascript" />
</head>
<body>
</body>
</html>

scripts/jQueryDemo.js

$(document).ready(function () {
    var Params = {};
    Params.type = 'GET';
    Params.url = 'jQueryDemo-Web-PocoDomainService.svc/' + 'JSON/' + 'GetPoco';
    Params.dataType = 'json';
    Params.success = function (data) {
        var returnedEntity;
        for (var i in data.GetPocoResult.RootResults) {
            returnedEntity = data.GetPocoResult.RootResults[i];
            $('body').append('<p>' + returnedEntity.EntityData + '</p>');
        }
    };
    $.ajax(Params);
});

At this point we can view the data on the client and will see a new paragraph tag containing “Entity 1 Server Data”.

Breaking down the jQuery code

Params.type = 'GET';

Using GET (instead of POST) for the query request.

Params.url = 'jQueryDemo-Web-PocoDomainService.svc/' + 'JSON/' + 'GetPoco';

String section 1: jQueryDemo.Web is the namespace that the PocoDomainService class exists in. Dashes are used instead of periods.

String section 2: JSON is the name given to the endpoint in the web.config ex:

<add name="JSON" type="Microsoft.ServiceModel.DomainServices.Hosting.JsonEndpointFactory,  Microsoft.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral,  PublicKeyToken=31bf3856ad364e35" />

String section 3: GetPoco is the name of the Query method defined in PocoDomainService.cs

Params.dataType = 'json';

The data should be in the json format.

Before I explain the next section I want to show the results of visiting the url:

{"GetPocoResult":
    {"TotalCount":1,"RootResults":
        [{"EntityData":"Entity 1 Server Data","EntityKey":"1"}]
    }
}

Now we can see that there is a GetPocoResult object with a RootResults array containing our entity. Knowing this we can loop through each entity in the RootResults array and process it. In this case we simply append the EntityData inside <p> tags to the <body>.

Params.success = function (data) {
    var returnedEntity;
    for (var i in data.GetPocoResult.RootResults) {
        returnedEntity = data.GetPocoResult.RootResults[i];
        $('body').append('<p>' + returnedEntity.EntityData + '</p>');
    }
};

Multiple Entities

Let’s add a few more entities to the PocoDomainService constructor.

public PocoDomainService()
{
    pocoList = new List();
    pocoList.Add(new PocoEntity() { EntityKey = "1", EntityData = "Entity 1 Server Data" });
    pocoList.Add(new PocoEntity() { EntityKey = "2", EntityData = "Entity 2 Server Data" });
    pocoList.Add(new PocoEntity() { EntityKey = "3", EntityData = "Entity 3 Server Data" });
}

Now the returned string looks like this. You should notice jQueryDemo.js doesn’t need to be updated to handle multiple entities.

{"GetPocoResult":
    {"TotalCount":3,"RootResults":
          [{"EntityData":"Entity 1 Server Data","EntityKey":"1"},
           {"EntityData":"Entity 2 Server Data","EntityKey":"2"},
           {"EntityData":"Entity 3 Server Data","EntityKey":"3"}]
    }
}