Events-MVC (example with htmx)

This commit is contained in:
Boris Milašinović
2026-04-25 22:21:35 +02:00
parent eb04483417
commit 0ee1b22f61
114 changed files with 7966 additions and 0 deletions

View File

@@ -0,0 +1,171 @@
@model PagedList<Events.MVC.Models.Countries.CountryViewModel>
@{
ViewData[Constants.ViewDataKeys.Title] = "Countries";
ViewData[Constants.ViewDataKeys.HeaderActionLabel] = "New country";
ViewData[Constants.ViewDataKeys.HeaderActionTarget] = "#create-country-panel";
}
<div class="d-flex flex-column gap-4">
<section id="create-country-panel" class="collapse">
<div class="card border-0 shadow-sm">
<div class="card-body">
<h2 class="h5 mb-3">Add a new country</h2>
<div id="create-country-form">
<partial name="_CreateCountryForm" model='new Events.MVC.Models.Countries.CountryViewModel()' />
</div>
</div>
</div>
</section>
<partial name="_CountriesList" model="Model" />
</div>
@section Scripts {
<script>
var countryToastVariantError = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.ToastVariants.Error));
var countryToastTitleError = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.ToastTitles.Error));
function reindexCountryTranslations(editor) {
var prefix = editor.dataset.prefix || "Translations";
var rows = editor.querySelectorAll("[data-translation-row]");
rows.forEach(function (row, index) {
row.querySelectorAll("[data-field]").forEach(function (input) {
input.name = prefix + "[" + index + "]." + input.dataset.field;
});
});
editor.querySelectorAll("[data-remove-translation]").forEach(function (button) {
button.disabled = rows.length === 1 && button.hasAttribute("data-keep-one");
});
}
function ensureCountryTranslationNames(editor) {
editor.querySelectorAll("[data-translation-row]").forEach(function (row) {
row.querySelectorAll("input[name]").forEach(function (input) {
var match = input.name.match(/\.([^.]+)$/);
if (match) {
input.dataset.field = match[1];
}
});
});
reindexCountryTranslations(editor);
}
function validateCountryTranslations(form) {
var editor = form.querySelector("[data-country-translations]");
if (!editor) {
return true;
}
var rows = editor.querySelectorAll("[data-translation-row]");
for (var i = 0; i < rows.length; i++) {
var languageInput = rows[i].querySelector("[data-field='LanguageCode'], input[name$='.LanguageCode']");
var nameInput = rows[i].querySelector("[data-field='Name'], input[name$='.Name']");
var language = languageInput ? languageInput.value.trim() : "";
var name = nameInput ? nameInput.value.trim() : "";
if ((language && !name) || (!language && name)) {
showAppToast({
variant: countryToastVariantError,
title: countryToastTitleError,
message: "Every translation row must contain both a language code and a translation."
});
if (!language && languageInput) {
languageInput.focus();
} else if (nameInput) {
nameInput.focus();
}
return false;
}
}
return true;
}
document.body.addEventListener("click", function (event) {
var addButton = event.target.closest("[data-add-translation]");
if (addButton) {
var editor = addButton.closest("[data-country-translations]");
var template = editor ? editor.querySelector("[data-translation-template]") : null;
var list = editor ? editor.querySelector("[data-translation-list]") : null;
if (!editor || !template || !list) {
return;
}
list.insertAdjacentHTML("beforeend", template.innerHTML.trim());
reindexCountryTranslations(editor);
return;
}
var removeButton = event.target.closest("[data-remove-translation]");
if (removeButton) {
var row = removeButton.closest("[data-translation-row]");
var owner = removeButton.closest("[data-country-translations]");
var rows = owner ? owner.querySelectorAll("[data-translation-row]") : [];
if (!row || !owner || rows.length <= 1) {
return;
}
row.remove();
reindexCountryTranslations(owner);
}
});
document.body.addEventListener("submit", function (event) {
var form = event.target;
if (!(form instanceof HTMLFormElement)) {
return;
}
if (!form.matches("#create-country-form form, tr[id^='country-'] form")) {
return;
}
if (!validateCountryTranslations(form)) {
event.preventDefault();
}
});
document.body.addEventListener("htmx:afterSwap", function (event) {
if (event.target && (event.target.id === "create-country-form" || event.target.id === "countries-list" || event.target.id.indexOf("country-") === 0)) {
document.querySelectorAll("[data-country-translations]").forEach(ensureCountryTranslationNames);
}
});
document.querySelectorAll("[data-country-translations]").forEach(ensureCountryTranslationNames);
document.body.addEventListener(@Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.HtmxEvents.CountryCreated)), function () {
var form = document.querySelector("#create-country-form form");
if (form) {
form.reset();
}
var editor = document.querySelector("#create-country-form [data-country-translations]");
if (editor) {
var rows = editor.querySelectorAll("[data-translation-row]");
rows.forEach(function (row, index) {
if (index > 0) {
row.remove();
} else {
row.querySelectorAll("input").forEach(function (input) {
input.value = "";
});
}
});
reindexCountryTranslations(editor);
}
var panel = document.getElementById("create-country-panel");
if (panel && window.bootstrap) {
bootstrap.Collapse.getOrCreateInstance(panel).hide();
}
});
</script>
}

View File

@@ -0,0 +1,171 @@
@model PagedList<Events.MVC.Models.Countries.CountryViewModel>
<section class="card border-0 shadow-sm" id="countries-list">
<div class="card-body">
<div id="countries-state" class="d-none">
<input type="hidden" name="page" value="@Model.PagingInfo.CurrentPage" />
<input type="hidden" name="pageSize" value="@Model.PagingInfo.ItemsPerPage" />
<input type="hidden" name="sorts" value="@Model.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.PagingInfo.Filters" />
</div>
<form
asp-action="Index"
method="get"
class="d-flex justify-content-between align-items-start gap-3 flex-wrap flex-lg-nowrap mb-4"
hx-get="@Url.Action("Index", "Countries")"
hx-target="#countries-list"
hx-swap="outerHTML"
hx-push-url="true"
onsubmit="var input=this.querySelector('[data-name-filter-input]'); var filters=this.querySelector('[name=filters]'); filters.value=input && input.value.trim() ? 'Name' + String.fromCharCode(64) + '=*' + input.value.trim() : ''; this.querySelector('[name=page]').value='1';">
<input type="hidden" name="page" value="1" />
<input type="hidden" name="pageSize" value="@Model.PagingInfo.ItemsPerPage" />
<input type="hidden" name="sorts" value="@Model.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.PagingInfo.Filters" />
<div class="d-flex align-items-center gap-3 pt-2">
<h2 class="h5 mb-0">Countries list</h2>
<span class="badge text-bg-light">@(Model.PagingInfo.IsFiltered ? $"{Model.PagingInfo.FilteredItemsCount} / {Model.PagingInfo.TotalItemsCount}" : Model.PagingInfo.TotalItemsCount.ToString())</span>
</div>
<div class="d-flex align-items-center gap-2 flex-nowrap ms-auto">
<input
id="countryNameFilter"
value="@Model.PagingInfo.NameFilter"
data-name-filter-input
class="form-control"
style="max-width: 18rem;"
placeholder="Search by country name"
aria-label="Filter by country name" />
<button type="submit" class="btn btn-outline-primary">Filter</button>
@if (Model.PagingInfo.IsFiltered)
{
<a
asp-action="Index"
asp-route-page="1"
asp-route-pageSize="@Model.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.PagingInfo.Sorts"
asp-route-filters=""
class="btn btn-outline-secondary"
hx-get="@Url.Action("Index", "Countries", new { page = 1, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.Sorts, filters = string.Empty })"
hx-target="#countries-list"
hx-swap="outerHTML"
hx-push-url="true">
Clear
</a>
}
</div>
</form>
<div class="table-responsive">
<table class="table align-middle mb-0">
<thead>
<tr>
<th>
<a
asp-action="Index"
asp-route-page="@Model.PagingInfo.CurrentPage"
asp-route-pageSize="@Model.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.PagingInfo.ToggleSort("Code")"
asp-route-filters="@Model.PagingInfo.Filters"
class="link-dark link-underline-opacity-0"
hx-get="@Url.Action("Index", "Countries", new { page = Model.PagingInfo.CurrentPage, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.ToggleSort("Code"), filters = Model.PagingInfo.Filters })"
hx-target="#countries-list"
hx-swap="outerHTML"
hx-push-url="true">
Code@(Model.PagingInfo.IsSortedBy("Code") ? (Model.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>
<a
asp-action="Index"
asp-route-page="@Model.PagingInfo.CurrentPage"
asp-route-pageSize="@Model.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.PagingInfo.ToggleSort("Alpha3")"
asp-route-filters="@Model.PagingInfo.Filters"
class="link-dark link-underline-opacity-0"
hx-get="@Url.Action("Index", "Countries", new { page = Model.PagingInfo.CurrentPage, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.ToggleSort("Alpha3"), filters = Model.PagingInfo.Filters })"
hx-target="#countries-list"
hx-swap="outerHTML"
hx-push-url="true">
Alpha-3@(Model.PagingInfo.IsSortedBy("Alpha3") ? (Model.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>
<a
asp-action="Index"
asp-route-page="@Model.PagingInfo.CurrentPage"
asp-route-pageSize="@Model.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.PagingInfo.ToggleSort("Name")"
asp-route-filters="@Model.PagingInfo.Filters"
class="link-dark link-underline-opacity-0"
hx-get="@Url.Action("Index", "Countries", new { page = Model.PagingInfo.CurrentPage, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.ToggleSort("Name"), filters = Model.PagingInfo.Filters })"
hx-target="#countries-list"
hx-swap="outerHTML"
hx-push-url="true">
Name@(Model.PagingInfo.IsSortedBy("Name") ? (Model.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th class="text-end"></th>
</tr>
</thead>
<tbody>
@if (Model.Data.Count == 0)
{
<tr>
<td colspan="4" class="text-body-secondary">No countries to display.</td>
</tr>
}
else
{
@foreach (var country in Model.Data)
{
<partial name="_CountryRow" model="country" />
}
}
</tbody>
</table>
</div>
<div class="d-flex justify-content-between align-items-center mt-4 gap-3 flex-wrap">
<div class="d-flex align-items-center gap-2 flex-wrap">
<small class="text-body-secondary">Page @Model.PagingInfo.CurrentPage of @Model.PagingInfo.TotalPages</small>
<form
asp-action="Index"
method="get"
class="d-inline-flex align-items-center gap-2"
hx-get="@Url.Action("Index", "Countries")"
hx-target="#countries-list"
hx-swap="outerHTML"
hx-push-url="true">
<input type="hidden" name="page" value="1" />
<input type="hidden" name="sorts" value="@Model.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.PagingInfo.Filters" />
<select
name="pageSize"
class="form-select form-select-sm"
style="width: auto;"
aria-label="Items per page"
onchange="this.form.requestSubmit()">
@{
int[] pageSizeOptions = [10, 20, 50, 100];
}
@foreach (var option in pageSizeOptions)
{
<option value="@option" selected="@(Model.PagingInfo.ItemsPerPage == option)">@option</option>
}
</select>
</form>
</div>
<pager
page-info="@Model.PagingInfo"
page-action="Index"
page-title="Enter a page number and press Enter"
page-target="#countries-list"
page-swap="outerHTML"
page-push-url="true">
</pager>
</div>
</div>
</section>

View File

@@ -0,0 +1,44 @@
@model Events.MVC.Models.Countries.CountryViewModel
<tr id="country-@Model.Code">
<td>@Model.Code</td>
<td colspan="3">
<form
asp-action="Edit"
asp-route-id="@Model.Code"
method="post"
hx-post="@Url.Action("Edit", "Countries", new { id = Model.Code })"
hx-target="#country-@Model.Code"
hx-swap="outerHTML">
@Html.AntiForgeryToken()
<input asp-for="Code" type="hidden" />
<div asp-validation-summary="ModelOnly" class="text-danger small mb-2"></div>
<div class="row g-2 align-items-start">
<div class="col-sm-3 col-lg-2">
<input asp-for="Alpha3" class="form-control text-uppercase" />
<span asp-validation-for="Alpha3" class="text-danger small"></span>
</div>
<div class="col-lg-5">
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger small"></span>
</div>
<div class="col-md-auto">
<button type="submit" class="btn btn-sm btn-primary">Save</button>
</div>
<div class="col-md-auto">
<button
type="button"
class="btn btn-sm btn-outline-secondary"
hx-get="@Url.Action("Row", "Countries", new { id = Model.Code })"
hx-target="#country-@Model.Code"
hx-swap="outerHTML">
Cancel
</button>
</div>
<div class="col-12">
<partial name="_CountryTranslationsEditor" model="Model.Translations" view-data='new ViewDataDictionary(ViewData) { ["Prefix"] = "Translations" }' />
</div>
</div>
</form>
</td>
</tr>

View File

@@ -0,0 +1,33 @@
@model Events.MVC.Models.Countries.CountryViewModel
<tr id="country-@Model.Code">
<td>@Model.Code</td>
<td>@Model.Alpha3</td>
<td>@Model.Name</td>
<td class="text-end">
<div class="d-inline-flex gap-2">
<button
type="button"
class="btn btn-sm btn-outline-primary"
hx-get="@Url.Action("EditRow", "Countries", new { id = Model.Code })"
hx-target="#country-@Model.Code"
hx-swap="outerHTML">
Edit
</button>
<form
asp-action="Delete"
asp-route-id="@Model.Code"
method="post"
class="d-inline"
hx-post="@Url.Action("Delete", "Countries", new { id = Model.Code })"
hx-include="#countries-state"
hx-target="#countries-list"
hx-swap="outerHTML"
hx-confirm="Delete country '@Model.Name'?">
@Html.AntiForgeryToken()
<button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
</form>
</div>
</td>
</tr>

View File

@@ -0,0 +1,47 @@
@model IList<Events.MVC.Models.Countries.CountryTranslationViewModel>
@{
var prefix = (string?)ViewData[Constants.ViewDataKeys.Prefix] ?? "Translations";
var canRemoveRows = (bool?)ViewData[Constants.ViewDataKeys.CanRemoveRows] ?? true;
var rows = Model.Count == 0 ? [new Events.MVC.Models.Countries.CountryTranslationViewModel()] : Model;
}
<div class="country-translations-editor" data-country-translations data-prefix="@prefix">
<div class="d-flex justify-content-between align-items-center gap-2 mb-2">
<span class="form-label mb-0">Translations</span>
<button type="button" class="btn btn-sm btn-outline-secondary" data-add-translation>Add translation</button>
</div>
<div class="d-flex flex-column gap-2" data-translation-list>
@for (var i = 0; i < rows.Count; i++)
{
<div class="row g-2 align-items-start" data-translation-row>
<div class="col-sm-3">
<input name="@($"{prefix}[{i}].LanguageCode")" value="@rows[i].LanguageCode" class="form-control" placeholder="en" />
</div>
<div class="col-sm-7">
<input name="@($"{prefix}[{i}].Name")" value="@rows[i].Name" class="form-control" placeholder="English name" />
</div>
<div class="col-sm-2 d-grid">
<button type="button" class="btn btn-outline-danger" data-remove-translation @(!canRemoveRows ? "data-keep-one" : null) @(rows.Count == 1 && !canRemoveRows ? "disabled" : null)>Remove</button>
</div>
</div>
}
</div>
<template data-translation-template>
<div class="row g-2 align-items-start" data-translation-row>
<div class="col-sm-3">
<input class="form-control" data-field="LanguageCode" placeholder="en" />
</div>
<div class="col-sm-7">
<input class="form-control" data-field="Name" placeholder="English name" />
</div>
<div class="col-sm-2 d-grid">
<button type="button" class="btn btn-outline-danger" data-remove-translation @(!canRemoveRows ? "data-keep-one" : null)>Remove</button>
</div>
</div>
</template>
<div class="form-text">Enter a language code such as <code>en</code>, <code>de</code>, or <code>hr</code>.</div>
</div>

View File

@@ -0,0 +1,36 @@
@model Events.MVC.Models.Countries.CountryViewModel
<form
asp-action="Create"
method="post"
hx-post="@Url.Action("Create", "Countries")"
hx-include="#countries-state"
hx-target="#countries-list"
hx-swap="outerHTML">
@Html.AntiForgeryToken()
<div asp-validation-summary="ModelOnly" class="text-danger small mb-3"></div>
<div class="row g-3 align-items-end">
<div class="col-sm-3 col-lg-2">
<label asp-for="Code" class="form-label"></label>
<input asp-for="Code" class="form-control text-uppercase" />
<span asp-validation-for="Code" class="text-danger small"></span>
</div>
<div class="col-sm-3 col-lg-2">
<label asp-for="Alpha3" class="form-label"></label>
<input asp-for="Alpha3" class="form-control text-uppercase" />
<span asp-validation-for="Alpha3" class="text-danger small"></span>
</div>
<div class="col-lg-5">
<label asp-for="Name" class="form-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger small"></span>
</div>
<div class="col-sm-auto">
<button type="submit" class="btn btn-primary">Add country</button>
</div>
</div>
<div class="mt-4">
<partial name="_CountryTranslationsEditor" model="Model.Translations" view-data='new ViewDataDictionary(ViewData) { ["Prefix"] = "Translations", ["CanRemoveRows"] = false }' />
</div>
</form>