SharePoint 2013 Hosted App (Part 3) – Access list from SharePoint Hosted App

SharePoint Hosted App series:

Following from my SharePoint Hosted App series, In this post I would like to show you how you could access a list from your SharePoint Hosted App.

Without further ado, please find below the list of steps to add SharePoint Hosted App Part:

1. Continue from previous solution in Part 2, we need to provision the list. To do that, I created new site column

myfirstapp18.2

2. Create new content type

myfirstapp18.3

myfirstapp18.4

3. Create new list and assign the content type

myfirstapp18.6

myfirstapp18.7

myfirstapp18.8

4. Update Default.aspx to add drop down control to show all list items

<%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>
<%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="VB" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>
    <meta name="WebPartPageExpansion" content="full" />

    <!-- Add your CSS styles to the following file -->
    <link rel="Stylesheet" type="text/css" href="../Content/App.css" />
    <!-- Add your JavaScript to the following file -->
    <script type="text/javascript" src="../Scripts/App.js"></script>
</asp:Content>

<%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
    Page Title
</asp:Content>

<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <div id="message">
        Hello ...
    </div>

    <div>
        <input id="clickMe" type="button" value="I can guess your name" />
    </div>

    <div id="myHomeTown">
    </div>
</asp:Content>

5. Update App.js to include all methods required

// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
    MyFirstApp = {
        element: '',
        loadUrl: '',
        createUrl: '',
        user: '',
        init: function (element) {
            var context = SP.ClientContext.get_current();
            var user = context.get_web().get_currentUser();
            context.load(user);

            MyFirstApp.element = element;
            MyFirstApp.loadUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Cities')/items?$select=Title,Country";
            MyFirstApp.createUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Cities')/items";
            MyFirstApp.user = user;
        },
        load: function () {
            $.ajax({
                url: MyFirstApp.loadUrl,
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
                success: MyFirstApp.onLoadSuccess,
                error: MyFirstApp.onLoadError
            });
        },
        onLoadSuccess: function (data) {
            var results = data.d.results;
            var html = "My sweet home town: <select>";
            for (var i = 0; i < results.length ; i++) {
                html += "<option value='" + results[i].Title + "'>" + results[i].Title + ", " + results[i].Country + "</option>";
            }
            html += "</select>";
            MyFirstApp.element.html(html);
        },
        onLoadError: function (errMsg) {
            MyFirstApp.element.html(JSON.stringify(errMsg));
        },
        add: function (city, country) {
            var itemType = "SP.Data.CitiesListItem";
            var item = {
                "__metadata": { "type": itemType },
                "Title": city,
                "Country": country,
            };

            $.ajax({
                url: MyFirstApp.createUrl,
                type: "POST",
                contentType: "application/json;odata=verbose",
                data: JSON.stringify(item),
                headers: {
                    "Accept": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val()
                },
                success: MyFirstApp.onAddSuccess,
                error: MyFirstApp.onAddError
            });
        },
        onAddSuccess: function () {

        },
        onAddError: function (errMsg) {
            MyFirstApp.element.html(JSON.stringify(errMsg));
        },
        getUserName: function () {
            var context = SP.ClientContext.get_current();
            var user = context.get_web().get_currentUser();
            context.load(user);
            context.executeQueryAsync(MyFirstApp.onGetUserNameSuccess, MyFirstApp.onGetUserNameError);
        },
        onGetUserNameSuccess: function () {
            $('#message').text('Hello ' + MyFirstApp.user.get_title());
        },
        onGetUserNameError: function (sender, args) {
            $('#message').text('Failed to get user name. Error:' + args.get_message());
        }
    }

    // initialization
    MyFirstApp.init($('#myHomeTown'));

    // attach clickMe onclick event
    $('#clickMe').onclick = MyFirstApp.getUserName();

    // add items into Cities list 
    MyFirstApp.add("Jakarta", "Indonesia");
    MyFirstApp.add("Melbourne", "Australia");
    MyFirstApp.add("Cleveland", "USA");
    MyFirstApp.add("Boston", "USA");

    // populate dropdown from Cities list
    MyFirstApp.load();
});

6. Update App.manifest to provide app Read permission to access the list

myfirstapp19.2

7. Rebuild the solution and Package the app

myfirstapp6

myfirstapp8

8. Remove existing MyFirstApp from your Site Collection > Site Actions > Site Contents

myfirstapp17

9. Update MyFirstApp.app from App Catalog site

myfirstapp9

10. Browse to your Site Collection > Site Actions > Site Contents > Add an App > From your Organization > click MyFirstApp to add the custom app to your SharePoint site

myfirstapp1011. Result

myfirstapp20

Tagged: , , , , , , ,

4 thoughts on “SharePoint 2013 Hosted App (Part 3) – Access list from SharePoint Hosted App

  1. […] Part 3: Access list from SharePoint Hosted App […]

  2. […] Part 3: Access list from SharePoint Hosted App […]

  3. dineshramitc 07/12/2015 at 1:46 PM Reply

    Reblogged this on Dinesh Ram Kali..