Skip to main content
Home  › ... Razor

JavaScript API Tutorials

Tutorial HomeJavaScript

Use the sxc data API to get backend data

This page uses the sxc data API to get data from the backend and display it in a table with JavaScript.


In this tutorial you'll learn how to:
  • Create a $2sxc object using the current Module Id
  • Use the correct data source using .data()
  • Read data using the .getOne(id) query method
  • Read data using the .getAll() query method

Look at the content below to see the effect.

Output

Name Birthdate Poems
<table id="example-content" class="table">
  <thead>
    <tr>
      <th>Name</th>
      <th>Birthdate</th>
      <th>Poems</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

@{
  var data = new {
    moduleId = CmsContext.Module.Id
  };
}

@Kit.Page.TurnOn("window.sxcDataTutorial200.init()", data: data)

<script src="@App.Path/js/200-get-data.js" @Kit.Page.AssetAttributes()></script>

Source Code of 200-get-data.js

// Use an IFFE to ensure the variables are not exposed globaly
// See https://developer.mozilla.org/en-US/docs/Glossary/IIFE
(() => {
  // This is a more modern JS feature to deconstruct parameters
  // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
  function init({ moduleId }) {
    // Create a $2sxc object using the current Module Id
    const sxc = $2sxc(moduleId);

    // Get the data source using .data('xy')
    const poetsSvc = sxc.data('Poets');

    // Read data from the backend data source with the .getAll() query
    poetsSvc.getAll().then((poets) => {
      // pass poets to displayPoets
      displayPoets(poets);

      // Get data of first poet with .getOne(id) query and log it in the console
      poetsSvc.getOne(poets[0].Id).then((poet) => console.log(`Queried poet using .getOne(): ${poet}`));
    });
  }

  // Display example data in table
  function displayPoets(poets) {
    Array.prototype.forEach.call(poets.reverse(), (poet, poetIndex) => {
      // Make sure only 3 elements are shown
      if (poetIndex >= 3) return
      
      let tr = document.createElement('tr')
      
      addField(tr, poet.Name);
      addField(tr, new Date(poet.BirthDate).toLocaleDateString());
      addField(tr, poet.Poems);

      document.querySelector('#example-content > tbody').appendChild(tr)
    });
  }

  function addField(tr, text) {
    let td = document.createElement('td')
    td.innerText = text
    tr.appendChild(td)
  }

  // This tutorial uses turnOn, see turnOn tutorials
  const sDT = window.sxcDataTutorial200 = window.sxcDataTutorial200 || {};
  sDT.init = sDT.init || init;
})();

Source Code of this file

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials. Click to expand the code

@using ToSic.Razor.Blade;
@inherits Custom.Hybrid.Razor14
@{
  // Tell the page that we need the 2sxc Js APIs
  Kit.Page.Activate("2sxc.JsCore"); 
}
<!-- unimportant stuff, hidden -->


<div @Sys.PageParts.InfoWrapper()>
  @Html.Partial("../shared/DefaultInfoSection.cshtml")
  <div @Sys.PageParts.InfoIntro()>
      <h2>Use the sxc data API to get backend data</h2>
      <p>This page uses the sxc data API to get data from the backend and display it in a table with JavaScript.</p>
      <br>
      In this tutorial you'll learn how to:
      <ul>
        <li>
          Create a <code>$2sxc</code> object using the current Module Id
        </li>
        <li>
          Use the correct data source using <code>.data()</code>
        </li>
        <li>
          Read data using the <code>.getOne(id)</code> query method
        </li>
        <li>
          Read data using the <code>.getAll()</code> query method
        </li>
      </ul>
      <br>
      Look at the content below to see the effect. 
    </div>
  </div>

  <table id="example-content" class="table">
    <thead>
      <tr>
        <th>Name</th>
        <th>Birthdate</th>
        <th>Poems</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>

  @{
    var data = new {
      moduleId = CmsContext.Module.Id
    };
  }

  @Kit.Page.TurnOn("window.sxcDataTutorial200.init()", data: data)

  <script src="@App.Path/js/200-get-data.js" @Kit.Page.AssetAttributes()></script>



@* Footer *@
@Html.Partial("../Shared/Layout/FooterWithSource.cshtml", new { Sys = Sys })