Steps to create list in SharePoint host web

Add HTML button, given below, in your *.aspx page-

  1. <asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
  2. <div>
  3. <p id="message">
  4. <!-- The following content will be replaced with the user name when you run the app - see App.js -->
  5. <button type="button" id="btnCreate">Create SP List</button>
  6. </p>
  7. </div>
  8. </asp:Content>
Write the code, given below, on your *.js file-
  1. //get Current Context
  2. var context = SP.ClientContext.get_current();
  3. // This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
  4. $(document).ready(function () {
  5. console.log("page loading...")
  6. $("#btnCreate").click(function () {
  7. createList();
  8. });
  9. });
  10. /this method is used to create list in host web
  11. function createList() {
  12. //Get host web URL
  13. var hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
  14. //get app context using host web url
  15. var appCtxSite = new SP.AppContextSite(context, hostWebUrl);
  16. //get current web
  17. var currentWEB = appCtxSite.get_web();
  18. //create object for list creation
  19. var listCreationInfo = new SP.ListCreationInformation();
  20. listCreationInfo.set_title("sampleList");
  21. //provide template type - genericList is custom list template
  22. listCreationInfo.set_templateType(SP.ListTemplateType.genericList);
  23. // add list in host web
  24. var list = currentWEB.get_lists().add(listCreationInfo);
  25. context.load(list);
  26. context.executeQueryAsync(function () {
  27. alert("Sharepoint custom list is created Successfully..")
  28. }, function (sender, args) {
  29. onfail(sender, args);
  30. });
  31. }
  32. / This function is executed if the above call fails
  33. function onfail(sender, args) {
  34. alert('Failed to create list. Error:' + args.get_message());
  35. }
  36. // this method used split the query string
  37. function manageQueryStringParameter(paramToRetrieve) {
  38. var params = document.URL.split("?")[1].split("&");
  39. var strParams = "";
  40. for (var i = 0; i < params.length; i = i + 1) {
  41. var singleParam = params[i].split("=");
  42. if (singleParam[0] == paramToRetrieve) {
  43. return singleParam[1];
  44. }
  45. }
  46. }
Note- In app manifest file, provide full control permission to the site collection, as shown below-

output

Summary

In this article, we have explored, how to create a list in SharePoint hosting Web, using JavaScript Object Model (JSOM).