Thursday, October 31, 2013

Create an app to access a public OData source, Working with SharePoint 2013 REST service

http://msdn.microsoft.com/en-us/library/office/fp142380.aspx
vs2012->file->new->project c# ->office/sharepoint->apps->apps for sharepoint 2013-> "AppLevelECTB2"
AppLevelECTB2 -> right click -> add -> select "content types for external data source"
-> http://services.odata.org/Northwind/Northwind.svc
-> ODataWebNorthwindModel
click on "next" -> select "Customers" table [make sure select below check box] -> click on "finish"
go to AppLevelECTB2 -> Pages -> Default.aspx open 
add below div in place of "ContentPlaceHolderID"
  <div id="displayDiv"></div>
go to AppLevelECTB2 -> Scripts -> App.js open
add below javascript

$(document).ready(function () {

    //Namespace
    window.AppLevelECT = window.AppLevelECT || {};

    //Constructor
    AppLevelECT.Grid = function (hostElement, surlWeb) {
        this.hostElement = hostElement;
        if (surlWeb.length > 0 && surlWeb.substring(surlWeb.length - 1, surlWeb.length) != "/")
            surlWeb += "/";
        this.surlWeb = surlWeb;
    }

    //Prototype
    AppLevelECT.Grid.prototype = {

        init: function () {

            $.ajax({
                url: this.surlWeb + "_api/lists/getbytitle('Customers')/items?$select=BdcIdentity,CustomerID,ContactName",
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
                success: this.showItems
            });
        },

        showItems: function (data) {
            var items = [];

            items.push("<table>");
            items.push('<tr><td>Customer ID</td><td>Customer Name</td></tr>');

            $.each(data.d.results, function (key, val) {
                items.push('<tr id="' + val.BdcIdentity + '"><td>' +
                    val.CustomerID + '</td><td>' +
                    val.ContactName + '</td></tr>');
            });

            items.push("</table>");

            $("#displayDiv").html(items.join(''));
        }
    }

    ExecuteOrDelayUntilScriptLoaded(getCustomers, "sp.js");
});

function getCustomers() {
    var grid = new AppLevelECT.Grid($("#displayDiv"), _spPageContextInfo.webServerRelativeUrl);
    grid.init();
}

AppLevelECTB2 -> Right Click -> Deploy

Thank You.

No comments:

Post a Comment