@inherits Custom.Hybrid.Razor14
@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 AsList(App.Data["Poets"])) {
var membershipMd = AsList(poet.Metadata.OfType("DeadPoetSocietyMembership") as object);
<tr>
<td>@poet.Name</td>
<td>
@if (membershipMd.Any()) {
foreach (var membership in membershipMd) {
<span>
@membership.MembershipNumber
<a href="#" onclick="window.sxcDataTutorial240.del(@membership.EntityId)">delete</a>
</span>
}
} else {
<button type="button" class="btn btn-primary" onclick='window.sxcDataTutorial240.add("@poet.EntityGuid")'>
add membership (metadata)
</button>
}
</td>
</tr>
}
</tbody>
</table>
@* This tutorial uses turnOn, see turnOn tutorials *@
@Kit.Page.TurnOn("window.sxcDataTutorial240.init()", data: new {
moduleId = CmsContext.Module.Id
})
<script src="@App.Path/310-create-metadata.js" @Kit.Page.AssetAttributes()></script>
Source Code of 310-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;
})();