Consuming a REST based JSON service using WinJS in Windows 8 Metro - Day 3

Niladri.Biswas
Posted by in Windows Metro category on for Beginner level | Points: 250 | Views : 8414 red flag

In this article, we will look into as how can we consume a REST based JSON service using WinJS in Windows 8 Metro.


 Download source code for Consuming a REST based JSON service using WinJS in Windows 8 Metro - Day 3

Introduction

In this article, we will look into as how can we consume a REST based JSON service using WinJS in Windows 8 Metro.We will perform two experiment.

  1. Bind REST based JSON object to a TextBox Control
  2. Bind REST based JSON object to a ListView Control

Start the experiment

Fire up VS 2012 Ultimate 2012 RC. Click File ->New ->Project.From the available templates, choose "JavaScript" -> Blank App.Enter a suitable application name (say "JSON_Consume_WinJS") with a proper location and click on "OK" button

A.Bind REST based JSON object to a TextBox Control

Open the default.html page and do the below design

<body>
    <button id="btnSimpleRESTInvocation">Simple REST Service</button>
    <input id="txtResult" type="text" />
</body>

Open the "default.js" file and write the below

// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
    "use strict";
    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    WinJS.strictProcessing();
    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll());
            document.getElementById("btnSimpleRESTInvocation").addEventListener("click", FetchSimpleJSonRecord, false);
        }
    };
    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // args.setPromise().
    };
    function FetchSimpleJSonRecord(event) {
        WinJS
            .xhr(
                    { url: "http://localhost:35798/RestServiceImpl.svc/Result/88" }
                 )
            .then
                 (
                    function (response) {
                        var name = JSON.parse(response.responseText);
                        document.getElementById("txtResult").value = name.JSONResponseResult;
                    }
                 );
    }
    app.start();
})();

The WinJS.xhr function is use to perform cross domain request.

Our REST service is located at the specified URL.Once we get a successful response, we use the JSON.parse function to convert the JSON string to an object.

Finally we are displaying the result in the "txtResult" textbox control.

B.Bind REST based JSON object to a ListView Control

In this exercise, we will look into as how we can bind a JSON object that comes from a REST based service to a ListViewControl.

Open the default.html page and do the below design

<body>
<button id="btnBindJSONToListView">Binding REST Service To ListView</button>
<div id="divDisplayItems" data-win-control="WinJS.Binding.Template">
 <div>
  <table border="1">
   <tr>
    <td><b>EmployeeId</b></td>
    <td><b>EmployeeName</b></td>
    <td><b>ContactNumber</b></td>
     <td><b>LiveIn</b></td>

   </tr>
   <tr>
    <td><h4 data-win-bind="innerText: EmployeeId"></h4></td>
    <td><h4 data-win-bind="innerText: EmployeeName"></h4></td>
    <td><h4 data-win-bind="innerText: ContactNumber"></h4></td>
    <td><h4 data-win-bind="innerText: LiveIn"></h4></td>

   </tr>
  </table>
 </div>
</div>
<div
 id="dvListView"
 style="width:550px;height:500px"
 data-win-control="WinJS.UI.ListView"
 data-win-options="{itemDataSource :SourceData.itemList.dataSource, itemTemplate: select('#divDisplayItems'),layout : {type: WinJS.UI.ListLayout}}"
 >
</div>
</body>

Open the "default.js" file and first write the below code between the app alias and app.onactivated line

var app = WinJS.Application;
//Add the next line
WinJS.Namespace.define("SourceData",{itemList: new WinJS.Binding.List([])})
var activation = Windows.ApplicationModel.Activation;

Then in the "Click" event handler of "btnBindJSONToListView", invoke the below function

function BindListView(event)
{
 WinJS
  .xhr(
    { url: "http://localhost:35798/RestServiceImpl.svc/EmployeeList" }
    )
  .then
    (
    function (response) {
     var sourceData = JSON.parse(response.responseText);
     var datalist = new WinJS.Binding.List(sourceData.EmployeeDetailsResult);
     dvListView.winControl.itemDataSource = datalist.dataSource;
    }
    );
}

First we are defining a "Namespace" ("SourceData" here) at the top of the default.js file, prior to the activated event.We are creating an empty Binding List there.

Next after getting teh JSON response, we are binding it to the "dvListView" control that holds the data

The result is as under

N.B.~If you are new as how to create a RESTful WCF service, then here is a step by step guidance for that.

N.B.~Make sure that the RESTful service is running while you are playing with the sample

Conclusion

Hope you find this article useful.Thanks for reading and stay tune for more to appear.Attached is the zipped file that contains the WCF RESTful service application along with the experiment code of this tutorial.

Page copy protected against web site content infringement by Copyscape

About the Author

Niladri.Biswas
Full Name: Niladri Biswas
Member Level: Platinum
Member Status: Member
Member Since: 10/25/2010 11:04:24 AM
Country: India
Best Regards, Niladri Biswas
http://www.dotnetfunda.com
Technical Lead at HCL Technologies

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)