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.


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

@* Make sure anonymous users have the 2sxc JS API *@

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

@* 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
(() => {
  let deadPoetMembersSvc;

  // This is a more modern JS feature to deconstruct parameters
  // See
  function init({ moduleId }) {
    // Create a $2sxc object using the current Module Id
    const sxc = $2sxc(moduleId);

    // Create the Service for the DeadPoetSocietyMembership Data
    deadPoetMembersSvc ='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.`);

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

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