Overview To SharePoint Hosted Apps

SharePoint Add-ins are self-contained extensions of SharePoint websites that you create, and that run without custom code on the SharePoint server.

In SharePoint hosted apps, you can use almost all the SharePoint components like list, content type, pages etc.…

All business logic in a SharePoint-hosted add-in, use JavaScript, either directly on a custom page or as a JavaScript file that is referenced from a custom page. A JavaScript version of the SharePoint Object Model (JSOM) is available to make it simple for the add-in to perform create, read, update, and delete (CRUD) operations on SharePoint data.

Over View of Example

  1. Create List in Office 365 Site
  2. Create Project in Visual Studio (Selecting SharePoint Hosted App)
  3. Provide User Interface
  4. Business logic under .js file (Insert Data)
  5. Deploy the Solution to office 365 Site.

Let’s take an example of SharePoint hosted app.

Step - 1 (Create List in Office 365 Site)

Open your office 365 Share Point site and create one list. Below find the steps and screen shots to create list with columns.

  • Click on Site Settings
  • Select New Option -> Select App-> Select Custom List.
  • Provide List name ‘Employees’.

Now, we need to create some columns for this list.

  • On Ribbon, Go to List Settings-> Under Columns Section Create three new columns.
  • EmployeeName(Title Field renamed as EmployeeName), Salary, Address.















We have done creation of List with columns. Now, we have to insert the data to the list, using User Interface and business logic.

Step - 2 (Create Project in Visual Studio (Selecting SharePoint Hosted App)

  • Create a project name called ‘TestSharePointHostedApp’ by selecting SharePoint Add.
  • Provide the office 365 SharePoint Url and select the SharePoint-Hosted App option.
  • It will ask credentials for authenticating the Site. Provide UserName and Password.
  • It will automatically selects SharePoint Online and click on Finish button.

Below, find the Screenshots for creating the SharePoint Hosted App through Visual Studio, using SharePoint hosted app.













As of now, we have done creation of project through Visual studio. After creation of project, Project contains different hierarchy like pages, Scripts, AppManifest.xml and etc.

  • Pages folder contains Default.aspx page.
  • Scripts folder contains default scripts for usage of our pages.
  • AppManifest.xml explains general information about version, start page, permissions, language and etc.


Below find the screen shot for AppManifest.xml file.



Step - 3 (Provide User Interface)

We are going to provide some text boxes, labels, and buttons for Inserting and displaying the data.

  • Open default.aspx page under pages folder.
  • You will find different sections, like PlaceHolderAdditionalPageHead, PlaceHolderPageTitleInTitleArea, PlaceHolderMain .
  • Under PlaceHolderMain, write the below code for User Interface.
    1. <table class="centerTable">  
    2.      <tr>  
    3.          <td>  
    4.              <table>  
    5.   
    6.                  <tr>  
    7.                      <td><span style="color: red; font: bold;"></span>EmployeeName </td>  
    8.                      <td>  
    9.                          <input type="text" id="empName" class="csValue" size="40" />  
    10.                      </td>  
    11.                  </tr>  
    12.                  <tr>  
    13.                      <td><span style="color: red; font: bold;"></span>Salary </td>  
    14.                      <td>  
    15.                          <input type="text" id="empSalary" class="csValue" size="40" />  
    16.                      </td>  
    17.                  </tr>  
    18.                  <tr>  
    19.                      <td><span style="color: red; font: bold;"></span>Address </td>  
    20.                      <td>  
    21.                          <%-- <input type="text" id="FeedBack"  class="c1" />--%>  
    22.                          <textarea name="Text1" cols="40" rows="5" id="empAddress" class="csValue"></textarea>  
    23.                      </td>  
    24.                  </tr>  
    25.   
    26.   
    27.              </table>  
    28.               
    29.          </td>  
    30.   
    31.      </tr>  
    32.  </table>  
    33.  <table>  
    34.      <tr>  
    35.   
    36.          <td>  
    37.              <input type="button" value="Clear" id="btnClear" style="background-color: #4CAF50; border: none; color: white; padding: 7px 15px; text-align: center; text-decoration: none; display: inline-block; font-size: 14px; margin: 4px 2px; cursor: pointer;" />  
    38.          </td>  
    39.   
    40.   
    41.          <td>  
    42.              <input type="button" value="Submit" id="btnCreate" style="background-color: #4CAF50; border: none; color: white; padding: 7px 15px; text-align: center; text-decoration: none; display: inline-block; font-size: 14px; margin: 4px 2px; cursor: pointer;" />  
    43.          </td>  
    44.          
    45.      </tr>  
    46.   
    47.   
    48.   
    49.  </table>  
    50.   
    51.  <table>  
    52.      <tr>  
    53.          <td></td>  
    54.          <td>  
    55.              <div id="dvMessage"></div>  
    56.          </td>  
    57.      </tr>  
    58.   
    59.  </table>  
    60.  <table>  
    61.      <tr>  
    62.          <td>  
    63.   
    64.              <table id="tblEmployees" class="mytable">  
    65.              </table>  
    66.   
    67.          </td>  
    68.      </tr>  
    69.  </tabl  

After writing the above code, User Interface will look like the below. You will not get a result immediately. Don’t bother about this. I have given this screenshot just for reference.



Step - 4 (Business logic under .js file (Insert and Display Data))

After completion of user Interface, we need to write the business logic for Insertion and Display operations. You can write business logic in App.js file or same page (default.aspx), or you can take separate .js file.

For this example, I am taking App.js file to write business logic. Please follow the below steps to write the code under App.js file.

  • Write method for to get hostWebUrl, appWebUrl
    1.       Method Name: manageQueryStringParameter(Parameter))  
    2.   
    3.          
    4. tion manageQueryStringParameter(paramToRetrieve) {  
    5. var params =  
    6. document.URL.split("?")[1].split("&");  
    7. var strParams = "";  
    8. for (var i = 0; i < params.length; i = i + 1) {  
    9.     var singleParam = params[i].split("=");  
    10.     if (singleParam[0] == paramToRetrieve) {  
    11.         return singleParam[1];  
    12.     }  
    13. }  
  • Write Methods for Inserting and Display operations.

    Method names: DisplayEmployeeInfo(), InsertEmployeeInfo(), ClearEmployeeInfo()


  • Call the above methods for Insert, and Display buttons under $(document).ready(function () {}
    1. hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));  
    2. appWebUrl = decodeURIComponent(manageQueryStringParameter('SPAppWebUrl'));  
    3.   
    4.   
    5. DisplayEmployeeDetails();  
    6.   
    7. $("#btnCreate").on('click'function () {  
    8.     createEmployee();  
    9.     DisplayEmployeeDetails();  
    10.     
    11.   
    12. });  
    13.   
    14.   
    15. $("#btnClear").on('click'function () {  
    16.     $(".csValue").val('');  
    17. });  

The following method is used for retrieving data from the list and display in a table.

  1. //Get List items of Employee List  
  2. function DisplayEmployeeDetails() {  
  3.   
  4.     var contxt = new SP.ClientContext(appWebUrl);  
  5.     var appContxt = new SP.AppContextSite(contxt, hostWebUrl);  
  6.     var web = appContxt.get_web(); //Get the Web   
  7.     var list = web.get_lists().getByTitle("Employees"); //Get the List  
  8.     var empQuery = new SP.CamlQuery();   
  9.     empQuery.set_viewXml('<View><RowLimit></RowLimit>50</View>');  
  10.     var items = list.getItems(empQuery);  
  11.     contxt.load(list);  
  12.     contxt.load(items);  
  13.     var table = $("#tblEmployees");  
  14.     var html = "<thead><tr><th>EmployeeId</<th><th>Name</th><th>Salary</th><th>Address</th></tr></thead>";  
  15.   
  16.     //Execute the Query Asynchronously  
  17.     contxt.executeQueryAsync(  
  18.         Function.createDelegate(thisfunction () {  
  19.             var itemInfo = '';  
  20.             var enumerator = items.getEnumerator();  
  21.             while (enumerator.moveNext()) {  
  22.                 var currentEmpItem = enumerator.get_current();  
  23.                 html += "<tr><td>" + currentEmpItem.get_item('ID') + "</td><td>" + currentEmpItem.get_item('Title') + "</td><td>" + currentEmpItem.get_item('Salary') + "</td><td>" + currentEmpItem.get_item('Address') + "</td></tr>";  
  24.             }  
  25.             table.html(html);  
  26.         }),  
  27.         Function.createDelegate(this, onQueryFailedGet)  
  28.         );  
  29.   
  30. }  
  31.   
  32. function onQueryFailedGet() {  
  33.   
  34.     $("#dvMessage").text("Display failed  " + arguments[1].get_message());  
  35. }  
The following method is used for inserting the data to Employee List.
  1. //Insert data into Employee List.  
  2. function createEmployee() {  
  3.   
  4.     var contxt = new SP.ClientContext(appWebUrl);  
  5.     var appContxt = new SP.AppContextSite(contxt, hostWebUrl);  
  6.     var web = appContxt.get_web(); //Get the Web   
  7.     var list = web.get_lists().getByTitle("Employees"); //Get the List  
  8.     var listCreationInformation = new SP.ListItemCreationInformation();   
  9.     var listItem = list.addItem(listCreationInformation);  
  10.     listItem.set_item("Title", $("#empName").val());  
  11.     listItem.set_item("Salary", $("#empSalary").val());  
  12.     listItem.set_item("Address", $("#empAddress").val());  
  13.     listItem.update();  //Update the list Item.  
  14.     contxt.load(listItem);  
  15.     //Execute the batch Asynchronously  
  16.   
  17.     contxt.executeQueryAsync(  
  18.     Function.createDelegate(this, onQuerySucceededCreate),  
  19.     Function.createDelegate(this, onQueryFailedCreate));  
  20.   
  21. }  
  22.   
  23.   
  24. function onQuerySucceededCreate() {  
  25.   
  26.     $("#dvMessage").text("Employee Information Submitted Successfully");  
  27. }  
  28.   
  29. function onQueryFailedCreate() {  
  30.   
  31.     $("#dvMessage").text("Submission failed  " + arguments[1].get_message());  
  32. }  
And, I have used CSS for table as well as headers.

Open the Content-> App.css file and paste the below css.
  1. /* Place custom styles below */  
  2. table.mytable {  
  3.     border-collapsecollapse;  
  4.     width100%;  
  5. }  
  6.   
  7. th, td {  
  8.     text-alignleft;  
  9.     padding8px;  
  10. }  
  11.   
  12. tr:nth-child(even){background-color#f2f2f2}  
  13.   
  14. th {  
  15.     background-color#4CAF50;  
  16.     colorwhite;  
  17. }  
Finally, App.js file looks like below and copy paste the below code under App.js.
  1. //-------------------------------------------------------------------------------//  
  2. 'use strict';  
  3.   
  4. var hostWebUrl;  
  5. var appWebUrl;  
  6.   
  7. var context = SP.ClientContext.get_current();  
  8. var user = context.get_web().get_currentUser();  
  9.   
  10. // This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model  
  11. $(document).ready(function () {  
  12.   
  13.      
  14.       
  15.     hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));  
  16.     appWebUrl = decodeURIComponent(manageQueryStringParameter('SPAppWebUrl'));  
  17.   
  18.      
  19.     DisplayEmployeeDetails();  
  20.   
  21.     $("#btnCreate").on('click'function () {  
  22.         createEmployee();  
  23.         DisplayEmployeeDetails();  
  24.         
  25.   
  26.     });  
  27.   
  28.       
  29.     $("#btnClear").on('click'function () {  
  30.         $(".csValue").val('');  
  31.     });  
  32.   
  33. });  
  34.   
  35.   
  36.   
  37. function manageQueryStringParameter(paramToRetrieve) {  
  38.     var params =  
  39.     document.URL.split("?")[1].split("&");  
  40.     var strParams = "";  
  41.     for (var i = 0; i < params.length; i = i + 1) {  
  42.         var singleParam = params[i].split("=");  
  43.         if (singleParam[0] == paramToRetrieve) {  
  44.             return singleParam[1];  
  45.         }  
  46.     }  
  47. }  
  48.   
  49.   
  50.   
  51.   
  52. //Get List items of Employee List  
  53. function DisplayEmployeeDetails() {  
  54.   
  55.     var contxt = new SP.ClientContext(appWebUrl);  
  56.     var appContxt = new SP.AppContextSite(contxt, hostWebUrl);  
  57.     var web = appContxt.get_web(); //Get the Web   
  58.     var list = web.get_lists().getByTitle("Employees"); //Get the List  
  59.     var empQuery = new SP.CamlQuery();   
  60.     empQuery.set_viewXml('<View><RowLimit></RowLimit>50</View>');  
  61.     var items = list.getItems(empQuery);  
  62.     contxt.load(list);  
  63.     contxt.load(items);  
  64.     var table = $("#tblEmployees");  
  65.     var html = "<thead><tr><th>EmployeeId</<th><th>Name</th><th>Salary</th><th>Address</th></tr></thead>";  
  66.   
  67.     //Execute the Query Asynchronously  
  68.     contxt.executeQueryAsync(  
  69.         Function.createDelegate(thisfunction () {  
  70.             var itemInfo = '';  
  71.             var enumerator = items.getEnumerator();  
  72.             while (enumerator.moveNext()) {  
  73.                 var currentEmpItem = enumerator.get_current();  
  74.                 html += "<tr><td>" + currentEmpItem.get_item('ID') + "</td><td>" + currentEmpItem.get_item('Title') + "</td><td>" + currentEmpItem.get_item('Salary') + "</td><td>" + currentEmpItem.get_item('Address') + "</td></tr>";  
  75.             }  
  76.             table.html(html);  
  77.         }),  
  78.         Function.createDelegate(this, onQueryFailedGet)  
  79.         );  
  80.   
  81. }  
  82.   
  83. function onQueryFailedGet() {  
  84.   
  85.     $("#dvMessage").text("Display failed  " + arguments[1].get_message());  
  86. }  
  87.   
  88.   
  89.   
  90. //Insert data into Employee List.  
  91. function createEmployee() {  
  92.   
  93.     var contxt = new SP.ClientContext(appWebUrl);  
  94.     var appContxt = new SP.AppContextSite(contxt, hostWebUrl);  
  95.     var web = appContxt.get_web(); //Get the Web   
  96.     var list = web.get_lists().getByTitle("Employees"); //Get the List  
  97.     var listCreationInformation = new SP.ListItemCreationInformation();   
  98.     var listItem = list.addItem(listCreationInformation);  
  99.     listItem.set_item("Title", $("#empName").val());  
  100.     listItem.set_item("Salary", $("#empSalary").val());  
  101.     listItem.set_item("Address", $("#empAddress").val());  
  102.     listItem.update();  //Update the list Item.  
  103.     contxt.load(listItem);  
  104.     //Execute the batch Asynchronously  
  105.   
  106.     contxt.executeQueryAsync(  
  107.     Function.createDelegate(this, onQuerySucceededCreate),  
  108.     Function.createDelegate(this, onQueryFailedCreate));  
  109.   
  110. }  
  111.   
  112.   
  113. function onQuerySucceededCreate() {  
  114.   
  115.     $("#dvMessage").text("Employee Information Submitted Successfully");  
  116. }  
  117.   
  118. function onQueryFailedCreate() {  
  119.   
  120.     $("#dvMessage").text("Submission failed  " + arguments[1].get_message());  
  121. }  
  122.   
  123.   
  124. // This function prepares, loads, and then executes a SharePoint query to get the current users information  
  125. function getUserName() {  
  126.     context.load(user);  
  127.     context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);  
  128. }  
  129.   
  130. // This function is executed if the above call is successful  
  131. // It replaces the contents of the 'message' element with the user name  
  132. function onGetUserNameSuccess() {  
  133.     $('#message').text('Hello ' + user.get_title());  
  134.   
  135. }  
  136.   
  137. // This function is executed if the above call fails  
  138. function onGetUserNameFail(sender, args) {  
  139.     alert('Failed to get user name. Error:' + args.get_message());  
  140. }  
  141.   
  142. //------------------------------------------------------------//  
Step- 5 (Deploy the Solution to Office 365 Site)

Deploy the solution to Office 365 site. Follow these steps to deploy the solution.
  •  Right click on project and select the option Deploy.
  • Trust the App for the Site, Click on Trust it.
  • Add the Employee Details like Employee Name, Salary, Address and then, click on Submit button.
  • If you want, you can clear the data using Clear button.







We have done the Share point hosted app basic operations, like Insertion and Display the data. Please let me know if you have any queries.

  • Attaching code file as well. You can download and try it.

References used- https://msdn.microsoft.com/en-us/library/office/fp179930.aspx