Skip to main content
Home  › ... Razor

JavaScript Tutorial

Tutorial HomeJavaScript
The samples can differ based on your Razor base class or if you're running an old version.
Selected: Typed (2sxc 16+) Switch to Dynamic (Razor14 or below)

Use the sxc data API to create metadata

This page uses the sxc data API to create metadata in the backend.

In this tutorial you'll learn how to:

  • Create metadata for other entities using the javascript .create(..., ...) method
  • Delete existing items (so the demo doesn't grow uncontrollably) using the .delete(...) method

Look at the content below to see the effect.

Result

Name Memberships
Gale Hansen 225969 delete
Gerard Pitts 7892345 delete
Todd Anderson
Richard Cameron
Daniel
@inherits Custom.Hybrid.RazorTyped
@using ToSic.Razor.Blade

@* Make sure anonymous users have the 2sxc JS API *@
@Kit.Page.Activate("2sxc.JsCore")

<table id="example-content" class="table">
  <thead>
    <tr>
      <th>Name</th>
      <th>Memberships</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    @foreach (var poet in AsItems(App.Data["Poets"])) {
      var membershipMd = AsItems(poet.Metadata.OfType("DeadPoetSocietyMembership"));
      <tr>
        <td>@poet.Get("Name")</td>
        <td>
          @if (membershipMd.Any()) {
            foreach (var membership in membershipMd) {
              <span>
                @membership.Get("MembershipNumber")
                <a href="#" onclick="window.sxcDataTutorial240.del(@membership.Id)">delete</a>
              </span>
            }
          } else {
            <button type="button" class="btn btn-primary" onclick='window.sxcDataTutorial240.add("@poet.Guid")'>
              add membership (metadata)
            </button>
          }
        </td>
      </tr>
    }
  </tbody>
</table>

@* This tutorial uses turnOn, see turnOn tutorials *@
@Kit.Page.TurnOn("window.sxcDataTutorial240.init()", data: new {
  moduleId = MyContext.Module.Id
})

<script src="@App.Folder.Url/tutorials/js-edit/js/create-metadata.js" @Kit.Page.AssetAttributes()></script>

Source Code of create-metadata.js

// Use an IFFE to ensure the variables are not exposed globaly
// See https://developer.mozilla.org/en-US/docs/Glossary/IIFE
(() => {
  let deadPoetMembersSvc;

  // 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);

    // Create the Service for the DeadPoetSocietyMembership Data
    deadPoetMembersSvc = sxc.data('DeadPoetSocietyMembership');
  }

  function add(poetGuid) {
    // Create a random membership number
    const randomMemberId = Math.floor(Math.random() * 999999).toString();

    // Create data in the backend with .create(object, target) and reload page after
    deadPoetMembersSvc.create({ MembershipNumber: randomMemberId }, poetGuid)
      .then(() => {
        alert('Just created new metadata for ' + poetGuid + `. We pretend he's member ${randomMemberId}. Will reload the page now.`);
        location.reload();
      });
  }

  function del(id) {
    if (confirm("Delete this membership?"))
      deadPoetMembersSvc.delete(id).then(() => {
        alert(`Just deleted ${id}. Will reload page now.`);
        location.reload();
      });
  }

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