Introduction:
In this blog you will see how to get all the Site Content Types using KnockoutJS and CSOM in SharePoint 2013. Please refer my article to implement KnockoutJS in a SharePoint page.
Script:
  1. <script src="https://c986.sharepoint.com/SiteAssets/jquery-1.8.3.min.js"></script>
  2. <script src="https://c986.sharepoint.com/SiteAssets/knockout-3.1.0.js"></script>
  3. <script src="https://c986.sharepoint.com/SiteAssets/ko.sp-1.0.min.js"></script>
  4. <script>
  5. ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js");
  6. var completeCTList = null;
  7. var contentTypeCollection=null;
  8. // Class used for saving the property values.
  9. function CTList(name) {
  10. var self = this;
  11. self.Name = name;
  12. }
  13. // View Model - JavaScript that defines the data and behavior of your UI
  14. function CTListViewModel() {
  15. var self = this;
  16. // observableArray equivalent of a regular array,
  17. self.ContentTypes = ko.observableArray([]);
  18. self.AddContentTypes = function (name) {
  19. self.ContentTypes.push(new CTList(name));
  20. }
  21. }
  22. function MainFunction() {
  23. completeCTList = new CTListViewModel();
  24. // Retrieve the SharePoint Site Content Types
  25. retrieveContentTypes();
  26. // Activates knockout.js
  27. ko.applyBindings(completeCTList);
  28. }
  29. function retrieveContentTypes() {
  30. var clientContext = new SP.ClientContext.get_current();
  31. var list = clientContext.get_web().get_lists().getByTitle("Employee Details");
  32. this.contentTypeCollection = list.get_contentTypes();
  33. clientContext.load(contentTypeCollection);
  34. clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
  35. }
  36. function onQuerySucceeded(sender, args) {
  37. var contentTypeEnumerator = contentTypeCollection.getEnumerator();
  38. while (contentTypeEnumerator.moveNext()) {
  39. var content = contentTypeEnumerator.get_current();
  40. completeCTList.AddContentTypes(content.get_name());
  41. }
  42. }
  43. function onQueryFailed(sender, args) {
  44. alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
  45. }
  46. </script>
  47. <!-- view - HTML markup that defines the appearance of your UI -->
  48. <div id="divCTList">
  49. <h2>
  50. List Content Types</h2>
  51. <br />
  52. <table id="tblEmployeeList" border="1">
  53. <thead>
  54. <tr>
  55. <th>
  56. Name
  57. </th>
  58. </tr>
  59. </thead>
  60. <!-- Iterating through every list item using foreach of KO -->
  61. <tbody data-bind="foreach: ContentTypes">
  62. <tr>
  63. <td data-bind="text: Name">
  64. </td>
  65. </tr>
  66. </tbody>
  67. </table>
  68. </div>
Output:
Summary:
Thus in this blog you saw how to get all the list Content Types using KnockoutJS and CSOM in SharePoint 2013.