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,67 @@
namespace Events.MVC;
public static class Constants
{
public static class TempDataKeys
{
public const string ToastMessage = "ToastMessage";
public const string ToastVariant = "ToastVariant";
public const string ToastTitle = "ToastTitle";
}
public static class ToastVariants
{
public const string Success = "success";
public const string Error = "error";
}
public static class ToastTitles
{
public const string Success = "Success";
public const string Error = "Error";
public const string Notification = "Notification";
}
public static class ViewDataKeys
{
public const string Title = "Title";
public const string HeaderActionLabel = "HeaderActionLabel";
public const string HeaderActionTarget = "HeaderActionTarget";
public const string CreatePersonModel = "CreatePersonModel";
public const string Prefix = "Prefix";
public const string CanRemoveRows = "CanRemoveRows";
}
public static class HtmxHeaders
{
public const string Request = "HX-Request";
public const string Retarget = "HX-Retarget";
public const string Reswap = "HX-Reswap";
public const string Trigger = "HX-Trigger";
}
public static class HtmxEvents
{
public const string ShowToast = "show-toast";
public const string CountryCreated = "country-created";
public const string EventCreated = "event-created";
public const string PersonCreated = "person-created";
public const string RegistrationCreated = "registration-created";
public const string SportCreated = "sport-created";
}
public static class HtmxSwap
{
public const string OuterHtml = "outerHTML";
}
public static class Messages
{
public const string EmailOrContactPhoneRequired = "Email or contact phone is required.";
public const string CountriesRequiredForPeople = "At least one country must be created before adding people.";
public const string EventsRequiredForRegistrations = "At least one event must be created before adding registrations.";
public const string SportsRequiredForRegistrations = "At least one sport must be created before adding registrations.";
public const string PeopleRequiredForRegistrations = "At least one person must be created before adding registrations.";
public const string RegistrationDependenciesRequired = "At least one event, one person, and one sport are required before adding registrations.";
}
}

View File

@@ -0,0 +1,347 @@
using System.Text.Json;
#if POSTGRES
using Events.EF.Data.Postgres;
#else
using Events.EF.Data.MSSQL;
#endif
using Events.EF.Models;
using Events.MVC.Models;
using Events.MVC.Models.Countries;
using Events.MVC.Util.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Sieve.Models;
using Sieve.Services;
namespace Events.MVC.Controllers;
public class CountriesController : Controller
{
private readonly EventsContext ctx;
private readonly ISieveProcessor sieveProcessor;
private readonly PagingSettings pagingSettings;
public CountriesController(EventsContext ctx, ISieveProcessor sieveProcessor, IOptions<PagingSettings> pagingSettings)
{
this.ctx = ctx;
this.sieveProcessor = sieveProcessor;
this.pagingSettings = pagingSettings.Value;
}
public async Task<IActionResult> Index(SieveModel sieveModel)
{
var viewModel = await BuildCountriesListAsync(sieveModel);
if (Request.Headers.ContainsKey(Constants.HtmxHeaders.Request))
{
return PartialView("_CountriesList", viewModel);
}
return View(viewModel);
}
[HttpGet]
public async Task<IActionResult> Row(string id)
{
var country = await ctx.Countries
.AsNoTracking()
.Select(c => new CountryViewModel
{
Code = c.Code,
Alpha3 = c.Alpha3,
Name = c.Name
})
.FirstOrDefaultAsync(c => c.Code == id);
if (country is null)
{
return NotFound();
}
return PartialView("_CountryRow", country);
}
[HttpGet]
public async Task<IActionResult> EditRow(string id)
{
var country = await ctx.Countries
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Code == id);
if (country is null)
{
return NotFound();
}
return PartialView("_CountryEditRow", MapCountryToViewModel(country, includeTranslations: true));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CountryViewModel model, SieveModel sieveModel)
{
NormalizeTranslations(model);
ValidateTranslations(model);
if (!ModelState.IsValid)
{
Response.Headers[Constants.HtmxHeaders.Retarget] = "#create-country-form";
Response.Headers[Constants.HtmxHeaders.Reswap] = Constants.HtmxSwap.OuterHtml;
return PartialView("_CreateCountryForm", model);
}
var country = new Country
{
Code = model.Code.Trim().ToUpperInvariant(),
Alpha3 = model.Alpha3.Trim().ToUpperInvariant(),
Name = model.Name.Trim(),
Translations = SerializeTranslations(model.Translations)
};
ctx.Countries.Add(country);
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.CountryCreated] = true,
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = $"Country '{country.Name}' was added successfully."
}
});
var viewModel = await BuildCountriesListAsync(sieveModel);
return PartialView("_CountriesList", viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(string id, CountryViewModel model)
{
if (!string.Equals(id, model.Code, StringComparison.OrdinalIgnoreCase))
{
return BadRequest();
}
NormalizeTranslations(model);
ValidateTranslations(model);
if (!ModelState.IsValid)
{
return PartialView("_CountryEditRow", model);
}
var country = await ctx.Countries.FirstOrDefaultAsync(c => c.Code == id);
if (country is null)
{
return NotFound();
}
country.Alpha3 = model.Alpha3.Trim().ToUpperInvariant();
country.Name = model.Name.Trim();
country.Translations = SerializeTranslations(model.Translations);
await ctx.SaveChangesAsync();
return PartialView("_CountryRow", new CountryViewModel
{
Code = country.Code,
Alpha3 = country.Alpha3,
Name = country.Name
});
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(string id, SieveModel sieveModel)
{
var country = await ctx.Countries
.Include(c => c.People)
.FirstOrDefaultAsync(c => c.Code == id);
if (country is null)
{
return NotFound();
}
if (country.People.Count > 0)
{
Response.StatusCode = StatusCodes.Status409Conflict;
return Content("The country cannot be deleted because related people exist.");
}
ctx.Countries.Remove(country);
var deletedName = country.Name;
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = $"Country '{deletedName}' was deleted successfully."
}
});
var viewModel = await BuildCountriesListAsync(sieveModel);
return PartialView("_CountriesList", viewModel);
}
private async Task<PagedList<CountryViewModel>> BuildCountriesListAsync(SieveModel sieveModel)
{
sieveModel.SetDefaultPagingAndSorting(pagingSettings.PageSize, "Name");
var normalizedFilters = sieveModel.Filters?.Trim() ?? string.Empty;
var nameFilter = SieveModelExtensions.ExtractFilterValue(normalizedFilters, "Name");
var baseQuery = ctx.Countries
.AsNoTracking()
.Select(c => new CountryViewModel
{
Code = c.Code,
Alpha3 = c.Alpha3,
Name = c.Name
});
var totalCount = await baseQuery.CountAsync();
var filteredCount = string.IsNullOrWhiteSpace(normalizedFilters)
? totalCount
: await sieveProcessor
.Apply(
sieveModel,
baseQuery,
applyFiltering: true,
applySorting: false,
applyPagination: false)
.CountAsync();
var pagingInfo = new PagingInfo
{
FilteredItemsCount = filteredCount,
TotalItemsCount = totalCount,
ItemsPerPage = sieveModel.PageSize!.Value,
CurrentPage = sieveModel.Page!.Value,
Sorts = sieveModel.Sorts ?? "Name",
Filters = normalizedFilters,
NameFilter = nameFilter
};
if (pagingInfo.CurrentPage > pagingInfo.TotalPages)
{
pagingInfo.CurrentPage = pagingInfo.TotalPages;
sieveModel.Page = pagingInfo.CurrentPage;
}
var countries = await sieveProcessor
.Apply(sieveModel, baseQuery)
.ToListAsync();
return new PagedList<CountryViewModel>(countries, pagingInfo);
}
private void ValidateTranslations(CountryViewModel model)
{
var languages = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var hasErrors = false;
for (var i = 0; i < model.Translations.Count; i++)
{
var translation = model.Translations[i] ?? new CountryTranslationViewModel();
var language = translation.LanguageCode?.Trim() ?? string.Empty;
var name = translation.Name?.Trim() ?? string.Empty;
if (string.IsNullOrEmpty(language) && string.IsNullOrEmpty(name))
{
continue;
}
if (string.IsNullOrEmpty(language))
{
ModelState.AddModelError($"Translations[{i}].LanguageCode", "Enter a language code.");
hasErrors = true;
}
if (string.IsNullOrEmpty(name))
{
ModelState.AddModelError($"Translations[{i}].Name", "Enter a translation.");
hasErrors = true;
}
if (!string.IsNullOrEmpty(language) && !languages.Add(language))
{
ModelState.AddModelError($"Translations[{i}].LanguageCode", "The language code has already been entered.");
hasErrors = true;
}
}
if (hasErrors)
{
ModelState.AddModelError(string.Empty, "Check the translations. Every row must have both a language code and a translation, and language codes must be unique.");
}
}
private static void NormalizeTranslations(CountryViewModel model)
{
model.Translations ??= [];
model.Translations = model.Translations
.Where(t => t is not null)
.Select(t => new CountryTranslationViewModel
{
LanguageCode = t!.LanguageCode?.Trim().ToLowerInvariant() ?? string.Empty,
Name = t.Name?.Trim() ?? string.Empty
})
.ToList();
}
private static CountryViewModel MapCountryToViewModel(Country country, bool includeTranslations)
{
return new CountryViewModel
{
Code = country.Code,
Alpha3 = country.Alpha3,
Name = country.Name,
Translations = includeTranslations ? ParseTranslations(country.Translations) : []
};
}
private static List<CountryTranslationViewModel> ParseTranslations(string? translationsJson)
{
if (string.IsNullOrWhiteSpace(translationsJson))
{
return [];
}
try
{
var translations = JsonSerializer.Deserialize<Dictionary<string, string>>(translationsJson);
if (translations is null)
{
return [];
}
return translations
.OrderBy(t => t.Key, StringComparer.OrdinalIgnoreCase)
.Select(t => new CountryTranslationViewModel
{
LanguageCode = t.Key,
Name = t.Value
})
.ToList();
}
catch (JsonException)
{
return [];
}
}
private static string? SerializeTranslations(IEnumerable<CountryTranslationViewModel> translations)
{
var dictionary = translations
.Where(t => t is not null && !string.IsNullOrWhiteSpace(t.LanguageCode) && !string.IsNullOrWhiteSpace(t.Name))
.ToDictionary(t => t.LanguageCode.Trim().ToLowerInvariant(), t => t.Name.Trim(), StringComparer.OrdinalIgnoreCase);
return dictionary.Count == 0 ? null : JsonSerializer.Serialize(dictionary);
}
}

View File

@@ -0,0 +1,241 @@
using System.Text.Json;
#if POSTGRES
using Events.EF.Data.Postgres;
#else
using Events.EF.Data.MSSQL;
#endif
using Events.EF.Models;
using Events.MVC.Models;
using Events.MVC.Models.Events;
using Events.MVC.Util.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Sieve.Models;
using Sieve.Services;
namespace Events.MVC.Controllers;
public class EventsController : Controller
{
private readonly EventsContext ctx;
private readonly ISieveProcessor sieveProcessor;
private readonly PagingSettings pagingSettings;
public EventsController(EventsContext ctx, ISieveProcessor sieveProcessor, IOptions<PagingSettings> pagingSettings)
{
this.ctx = ctx;
this.sieveProcessor = sieveProcessor;
this.pagingSettings = pagingSettings.Value;
}
public async Task<IActionResult> Index(SieveModel sieveModel)
{
var viewModel = await BuildEventsListAsync(sieveModel);
if (Request.Headers.ContainsKey(Constants.HtmxHeaders.Request))
{
return PartialView("_EventsList", viewModel);
}
return View(viewModel);
}
[HttpGet]
public async Task<IActionResult> Row(int id)
{
var eventModel = await ctx.Events
.AsNoTracking()
.Select(e => new EventViewModel
{
Id = e.Id,
Name = e.Name,
EventDate = e.EventDate,
ParticipantsCount = e.Registrations.Count
})
.FirstOrDefaultAsync(e => e.Id == id);
if (eventModel is null)
{
return NotFound();
}
return PartialView("_EventRow", eventModel);
}
[HttpGet]
public async Task<IActionResult> EditRow(int id)
{
var eventModel = await ctx.Events
.AsNoTracking()
.Select(e => new EventViewModel
{
Id = e.Id,
Name = e.Name,
EventDate = e.EventDate
})
.FirstOrDefaultAsync(e => e.Id == id);
if (eventModel is null)
{
return NotFound();
}
return PartialView("_EventEditRow", eventModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(EventViewModel model, SieveModel sieveModel)
{
if (!ModelState.IsValid)
{
Response.Headers[Constants.HtmxHeaders.Retarget] = "#create-event-form";
Response.Headers[Constants.HtmxHeaders.Reswap] = Constants.HtmxSwap.OuterHtml;
return PartialView("_CreateEventForm", model);
}
var eventEntity = new Event
{
Name = model.Name,
EventDate = model.EventDate
};
ctx.Events.Add(eventEntity);
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.EventCreated] = true,
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = $"Event '{model.Name}' was added successfully."
}
});
var viewModel = await BuildEventsListAsync(sieveModel);
return PartialView("_EventsList", viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, EventViewModel model)
{
if (id != model.Id)
{
return BadRequest();
}
if (!ModelState.IsValid)
{
return PartialView("_EventEditRow", model);
}
var existingEvent = await ctx.Events.FirstOrDefaultAsync(e => e.Id == id);
if (existingEvent is null)
{
return NotFound();
}
existingEvent.Name = model.Name;
existingEvent.EventDate = model.EventDate;
await ctx.SaveChangesAsync();
return PartialView("_EventRow", new EventViewModel
{
Id = existingEvent.Id,
Name = existingEvent.Name,
EventDate = existingEvent.EventDate,
ParticipantsCount = await ctx.Registrations.CountAsync(r => r.EventId == existingEvent.Id)
});
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id, SieveModel sieveModel)
{
var eventEntity = await ctx.Events
.Include(e => e.Registrations)
.FirstOrDefaultAsync(e => e.Id == id);
if (eventEntity is null)
{
return NotFound();
}
if (eventEntity.Registrations.Count > 0)
{
Response.StatusCode = StatusCodes.Status409Conflict;
return Content("The event cannot be deleted because registrations exist.");
}
ctx.Events.Remove(eventEntity);
var deletedName = eventEntity.Name;
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = $"Event '{deletedName}' was deleted successfully."
}
});
var viewModel = await BuildEventsListAsync(sieveModel);
return PartialView("_EventsList", viewModel);
}
private async Task<PagedList<EventViewModel>> BuildEventsListAsync(SieveModel sieveModel)
{
sieveModel.SetDefaultPagingAndSorting(pagingSettings.PageSize, "EventDate");
var normalizedFilters = sieveModel.Filters?.Trim() ?? string.Empty;
var nameFilter = SieveModelExtensions.ExtractFilterValue(normalizedFilters, "Name");
var baseQuery = ctx.Events
.AsNoTracking()
.Select(e => new EventViewModel
{
Id = e.Id,
Name = e.Name,
EventDate = e.EventDate,
ParticipantsCount = e.Registrations.Count
});
var totalCount = await baseQuery.CountAsync();
var filteredCount = string.IsNullOrWhiteSpace(normalizedFilters)
? totalCount
: await sieveProcessor
.Apply(
sieveModel,
baseQuery,
applyFiltering: true,
applySorting: false,
applyPagination: false)
.CountAsync();
var pagingInfo = new PagingInfo
{
FilteredItemsCount = filteredCount,
TotalItemsCount = totalCount,
ItemsPerPage = sieveModel.PageSize!.Value,
CurrentPage = sieveModel.Page!.Value,
Sorts = sieveModel.Sorts ?? "EventDate",
Filters = normalizedFilters,
NameFilter = nameFilter
};
if (pagingInfo.CurrentPage > pagingInfo.TotalPages)
{
pagingInfo.CurrentPage = pagingInfo.TotalPages;
sieveModel.Page = pagingInfo.CurrentPage;
}
var events = await sieveProcessor
.Apply(sieveModel, baseQuery)
.ToListAsync();
return new PagedList<EventViewModel>(events, pagingInfo);
}
}

View File

@@ -0,0 +1,21 @@
using System.Diagnostics;
using Events.MVC.Models;
using Microsoft.AspNetCore.Mvc;
namespace Events.MVC.Controllers;
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Error()
{
return View(new ErrorViewModel
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
});
}
}

View File

@@ -0,0 +1,337 @@
using System.Text.Json;
#if POSTGRES
using Events.EF.Data.Postgres;
#else
using Events.EF.Data.MSSQL;
#endif
using Events.EF.Models;
using Events.MVC.Models;
using Events.MVC.Models.People;
using Events.MVC.Util.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Sieve.Models;
using Sieve.Services;
namespace Events.MVC.Controllers;
public class PeopleController : Controller
{
private readonly EventsContext ctx;
private readonly ISieveProcessor sieveProcessor;
private readonly PagingSettings pagingSettings;
public PeopleController(EventsContext ctx, ISieveProcessor sieveProcessor, IOptions<PagingSettings> pagingSettings)
{
this.ctx = ctx;
this.sieveProcessor = sieveProcessor;
this.pagingSettings = pagingSettings.Value;
}
public async Task<IActionResult> Index(SieveModel sieveModel)
{
if (!await ctx.Countries.AsNoTracking().AnyAsync())
{
TempData[Constants.TempDataKeys.ToastVariant] = Constants.ToastVariants.Error;
TempData[Constants.TempDataKeys.ToastTitle] = Constants.ToastTitles.Error;
TempData[Constants.TempDataKeys.ToastMessage] = Constants.Messages.CountriesRequiredForPeople;
return RedirectToAction("Index", "Countries");
}
var viewModel = await BuildPeopleListAsync(sieveModel);
if (Request.Headers.ContainsKey(Constants.HtmxHeaders.Request))
{
return PartialView("_PeopleList", viewModel);
}
ViewData[Constants.ViewDataKeys.CreatePersonModel] = new PersonViewModel
{
CountryOptions = await GetCountryOptionsAsync()
};
return View(viewModel);
}
[HttpGet]
public async Task<IActionResult> Row(int id)
{
var person = await ctx.People
.AsNoTracking()
.Select(p => new PersonViewModel
{
Id = p.Id,
FirstName = p.FirstName,
LastName = p.LastName,
FirstNameTranscription = p.FirstNameTranscription,
LastNameTranscription = p.LastNameTranscription,
FullName = p.FirstName + " " + p.LastName,
FullNameTranscription = p.FirstNameTranscription + " " + p.LastNameTranscription,
BirthDate = p.BirthDate,
CountryName = p.CountryCodeNavigation.Name,
RegistrationsCount = p.Registrations.Count
})
.FirstOrDefaultAsync(p => p.Id == id);
if (person is null)
{
return NotFound();
}
return PartialView("_PersonRow", person);
}
[HttpGet]
public async Task<IActionResult> EditRow(int id)
{
var person = await ctx.People
.AsNoTracking()
.Select(p => new PersonViewModel
{
Id = p.Id,
FirstName = p.FirstName,
LastName = p.LastName,
FirstNameTranscription = p.FirstNameTranscription,
LastNameTranscription = p.LastNameTranscription,
AddressLine = p.AddressLine,
PostalCode = p.PostalCode,
City = p.City,
AddressCountry = p.AddressCountry,
Email = p.Email,
ContactPhone = p.ContactPhone,
BirthDate = p.BirthDate,
DocumentNumber = p.DocumentNumber,
CountryCode = p.CountryCode
})
.FirstOrDefaultAsync(p => p.Id == id);
if (person is null)
{
return NotFound();
}
person.CountryOptions = await GetCountryOptionsAsync(person.CountryCode);
return PartialView("_PersonEditRow", person);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(PersonViewModel model, SieveModel sieveModel)
{
if (!ModelState.IsValid)
{
model.CountryOptions = await GetCountryOptionsAsync(model.CountryCode);
Response.Headers[Constants.HtmxHeaders.Retarget] = "#create-person-form";
Response.Headers[Constants.HtmxHeaders.Reswap] = Constants.HtmxSwap.OuterHtml;
return PartialView("_CreatePersonForm", model);
}
var person = new Person
{
FirstName = model.FirstName.TrimToNull(),
LastName = model.LastName.TrimToNull(),
FirstNameTranscription = model.FirstNameTranscription.Trim(),
LastNameTranscription = model.LastNameTranscription.Trim(),
AddressLine = model.AddressLine.TrimToNull(),
PostalCode = model.PostalCode.TrimToNull(),
City = model.City.TrimToNull(),
AddressCountry = model.AddressCountry.TrimToNull(),
Email = model.Email.TrimToNull(),
ContactPhone = model.ContactPhone.TrimToNull(),
BirthDate = model.BirthDate!.Value,
DocumentNumber = model.DocumentNumber.Trim(),
CountryCode = model.CountryCode.Trim().ToUpperInvariant()
};
ctx.People.Add(person);
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.PersonCreated] = true,
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = $"Person '{person.FirstName} {person.LastName}' was added successfully."
}
});
var viewModel = await BuildPeopleListAsync(sieveModel);
return PartialView("_PeopleList", viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, PersonViewModel model)
{
if (id != model.Id)
{
return BadRequest();
}
if (!ModelState.IsValid)
{
model.CountryOptions = await GetCountryOptionsAsync(model.CountryCode);
return PartialView("_PersonEditRow", model);
}
var person = await ctx.People.FirstOrDefaultAsync(p => p.Id == id);
if (person is null)
{
return NotFound();
}
person.FirstName = model.FirstName.TrimToNull();
person.LastName = model.LastName.TrimToNull();
person.FirstNameTranscription = model.FirstNameTranscription.Trim();
person.LastNameTranscription = model.LastNameTranscription.Trim();
person.AddressLine = model.AddressLine.TrimToNull();
person.PostalCode = model.PostalCode.TrimToNull();
person.City = model.City.TrimToNull();
person.AddressCountry = model.AddressCountry.TrimToNull();
person.Email = model.Email.TrimToNull();
person.ContactPhone = model.ContactPhone.TrimToNull();
person.BirthDate = model.BirthDate!.Value;
person.DocumentNumber = model.DocumentNumber.Trim();
person.CountryCode = model.CountryCode.Trim().ToUpperInvariant();
await ctx.SaveChangesAsync();
var rowModel = await ctx.People
.AsNoTracking()
.Where(p => p.Id == id)
.Select(p => new PersonViewModel
{
Id = p.Id,
FirstName = p.FirstName,
LastName = p.LastName,
FirstNameTranscription = p.FirstNameTranscription,
LastNameTranscription = p.LastNameTranscription,
FullName = p.FirstName + " " + p.LastName,
FullNameTranscription = p.FirstNameTranscription + " " + p.LastNameTranscription,
BirthDate = p.BirthDate,
CountryName = p.CountryCodeNavigation.Name,
RegistrationsCount = p.Registrations.Count
})
.FirstAsync();
return PartialView("_PersonRow", rowModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id, SieveModel sieveModel)
{
var person = await ctx.People
.Include(p => p.Registrations)
.FirstOrDefaultAsync(p => p.Id == id);
if (person is null)
{
return NotFound();
}
if (person.Registrations.Count > 0)
{
Response.StatusCode = StatusCodes.Status409Conflict;
return Content("The person cannot be deleted because registrations exist.");
}
ctx.People.Remove(person);
var deletedName = $"{person.FirstName} {person.LastName}";
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = $"Person '{deletedName}' was deleted successfully."
}
});
var viewModel = await BuildPeopleListAsync(sieveModel);
return PartialView("_PeopleList", viewModel);
}
private async Task<PeoplePageViewModel> BuildPeopleListAsync(SieveModel sieveModel)
{
sieveModel.SetDefaultPagingAndSorting(pagingSettings.PageSize, "LastNameTranscription");
var normalizedFilters = sieveModel.Filters?.Trim() ?? string.Empty;
var nameFilter = SieveModelExtensions.ExtractFilterValue(normalizedFilters, "FullNameTranscription");
var countryFilter = SieveModelExtensions.ExtractFilterValue(normalizedFilters, "CountryCode", "==");
var baseQuery = ctx.People
.AsNoTracking()
.Select(p => new PersonViewModel
{
Id = p.Id,
FirstName = p.FirstName,
LastName = p.LastName,
FirstNameTranscription = p.FirstNameTranscription,
LastNameTranscription = p.LastNameTranscription,
FullName = p.FirstName + " " + p.LastName,
FullNameTranscription = p.FirstNameTranscription + " " + p.LastNameTranscription,
CountryCode = p.CountryCode,
BirthDate = p.BirthDate,
CountryName = p.CountryCodeNavigation.Name,
RegistrationsCount = p.Registrations.Count
});
var totalCount = await baseQuery.CountAsync();
var filteredCount = string.IsNullOrWhiteSpace(normalizedFilters)
? totalCount
: await sieveProcessor
.Apply(
sieveModel,
baseQuery,
applyFiltering: true,
applySorting: false,
applyPagination: false)
.CountAsync();
var pagingInfo = new PagingInfo
{
FilteredItemsCount = filteredCount,
TotalItemsCount = totalCount,
ItemsPerPage = sieveModel.PageSize!.Value,
CurrentPage = sieveModel.Page!.Value,
Sorts = sieveModel.Sorts ?? "LastNameTranscription",
Filters = normalizedFilters,
NameFilter = nameFilter
};
if (pagingInfo.CurrentPage > pagingInfo.TotalPages)
{
pagingInfo.CurrentPage = pagingInfo.TotalPages;
sieveModel.Page = pagingInfo.CurrentPage;
}
var people = await sieveProcessor
.Apply(sieveModel, baseQuery)
.ToListAsync();
return new PeoplePageViewModel
{
People = new PagedList<PersonViewModel>(people, pagingInfo),
CountryOptions = await GetCountryOptionsAsync(countryFilter),
CountryFilter = countryFilter
};
}
private async Task<List<SelectListItem>> GetCountryOptionsAsync(string? selectedCode = null)
{
return await ctx.Countries
.AsNoTracking()
.OrderBy(c => c.Name)
.Select(c => new SelectListItem
{
Value = c.Code,
Text = c.Name,
Selected = c.Code == selectedCode
})
.ToListAsync();
}
}

View File

@@ -0,0 +1,430 @@
using System.Text.Json;
#if POSTGRES
using Events.EF.Data.Postgres;
#else
using Events.EF.Data.MSSQL;
#endif
using Events.EF.Models;
using Events.MVC.Models;
using Events.MVC.Models.Registrations;
using Events.MVC.Util.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Sieve.Models;
using Sieve.Services;
namespace Events.MVC.Controllers;
public class RegistrationsController : Controller
{
private readonly EventsContext ctx;
private readonly ISieveProcessor sieveProcessor;
private readonly PagingSettings pagingSettings;
public RegistrationsController(EventsContext ctx, ISieveProcessor sieveProcessor, IOptions<PagingSettings> pagingSettings)
{
this.ctx = ctx;
this.sieveProcessor = sieveProcessor;
this.pagingSettings = pagingSettings.Value;
}
public async Task<IActionResult> Index(int? eventId, SieveModel sieveModel)
{
var events = await GetEventOptionsAsync(eventId);
if (events.Count == 0)
{
TempData[Constants.TempDataKeys.ToastVariant] = Constants.ToastVariants.Error;
TempData[Constants.TempDataKeys.ToastTitle] = Constants.ToastTitles.Error;
TempData[Constants.TempDataKeys.ToastMessage] = Constants.Messages.EventsRequiredForRegistrations;
return RedirectToAction("Index", "Events");
}
if (!await ctx.Sports.AsNoTracking().AnyAsync())
{
TempData[Constants.TempDataKeys.ToastVariant] = Constants.ToastVariants.Error;
TempData[Constants.TempDataKeys.ToastTitle] = Constants.ToastTitles.Error;
TempData[Constants.TempDataKeys.ToastMessage] = Constants.Messages.SportsRequiredForRegistrations;
return RedirectToAction("Index", "Sports");
}
if (!await ctx.People.AsNoTracking().AnyAsync())
{
TempData[Constants.TempDataKeys.ToastVariant] = Constants.ToastVariants.Error;
TempData[Constants.TempDataKeys.ToastTitle] = Constants.ToastTitles.Error;
TempData[Constants.TempDataKeys.ToastMessage] = Constants.Messages.PeopleRequiredForRegistrations;
return RedirectToAction("Index", "People");
}
var selectedEventId = eventId ?? int.Parse(events[0].Value);
MarkSelectedEvent(events, selectedEventId);
var viewModel = await BuildPageViewModelAsync(selectedEventId, sieveModel, events);
if (Request.Headers.ContainsKey(Constants.HtmxHeaders.Request))
{
return PartialView("_RegistrationsPanel", viewModel);
}
return View(viewModel);
}
[HttpGet]
public async Task<IActionResult> Row(int id, int eventId)
{
var registration = await ctx.Registrations
.AsNoTracking()
.Where(r => r.Id == id && r.EventId == eventId)
.Select(r => new RegistrationViewModel
{
Id = r.Id,
EventId = r.EventId,
PersonId = r.PersonId,
SportId = r.SportId,
PersonName = r.Person.FirstName + " " + r.Person.LastName,
PersonTranscription = r.Person.FirstNameTranscription + " " + r.Person.LastNameTranscription,
CountryCode = r.Person.CountryCode,
CountryName = r.Person.CountryCodeNavigation.Name,
SportName = r.Sport.Name,
RegisteredAt = r.RegisteredAt
})
.FirstOrDefaultAsync();
if (registration is null)
{
return NotFound();
}
return PartialView("_RegistrationRow", registration);
}
[HttpGet]
public async Task<IActionResult> EditRow(int id, int eventId)
{
var registration = await ctx.Registrations
.AsNoTracking()
.Where(r => r.Id == id && r.EventId == eventId)
.Select(r => new RegistrationViewModel
{
Id = r.Id,
EventId = r.EventId,
PersonId = r.PersonId,
SportId = r.SportId,
RegisteredAt = r.RegisteredAt
})
.FirstOrDefaultAsync();
if (registration is null)
{
return NotFound();
}
await PopulateRegistrationOptionsAsync(registration);
return PartialView("_RegistrationEditRow", registration);
}
[HttpGet]
public async Task<IActionResult> PersonSuggestions(string? personLookup, string? countryFilter)
{
if (string.IsNullOrWhiteSpace(personLookup))
{
return PartialView("_PersonSuggestions", Array.Empty<SelectListItem>());
}
var searchTerm = personLookup.Trim().ToLowerInvariant();
var query = ctx.People
.AsNoTracking()
.Where(p =>
p.FirstNameTranscription.ToLower().Contains(searchTerm) ||
p.LastNameTranscription.ToLower().Contains(searchTerm) ||
(p.FirstNameTranscription + " " + p.LastNameTranscription).ToLower().Contains(searchTerm))
.AsQueryable();
if (!string.IsNullOrWhiteSpace(countryFilter))
{
query = query.Where(p => p.CountryCode == countryFilter);
}
var suggestions = await query
.OrderBy(p => p.LastName)
.ThenBy(p => p.FirstName)
.Take(10)
.Select(p => new SelectListItem
{
Value = p.Id.ToString(),
Text = p.FirstName + " " + p.LastName + "|" + p.FirstNameTranscription + " " + p.LastNameTranscription
})
.ToListAsync();
return PartialView("_PersonSuggestions", suggestions);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(RegistrationViewModel model, SieveModel sieveModel)
{
if (!await CanCreateRegistrationsAsync())
{
Response.StatusCode = StatusCodes.Status409Conflict;
return Content(Constants.Messages.RegistrationDependenciesRequired);
}
if (!ModelState.IsValid)
{
await PopulateRegistrationOptionsAsync(model);
Response.Headers[Constants.HtmxHeaders.Retarget] = "#create-registration-form";
Response.Headers[Constants.HtmxHeaders.Reswap] = Constants.HtmxSwap.OuterHtml;
return PartialView("_CreateRegistrationForm", model);
}
var registration = new Registration
{
EventId = model.EventId,
PersonId = model.PersonId,
SportId = model.SportId
};
ctx.Registrations.Add(registration);
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.RegistrationCreated] = true,
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = "Registration was added successfully."
}
});
var viewModel = await BuildPageViewModelAsync(model.EventId, sieveModel);
return PartialView("_RegistrationsPanel", viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, RegistrationViewModel model)
{
if (id != model.Id)
{
return BadRequest();
}
if (!ModelState.IsValid)
{
await PopulateRegistrationOptionsAsync(model);
return PartialView("_RegistrationEditRow", model);
}
var registration = await ctx.Registrations.FirstOrDefaultAsync(r => r.Id == id && r.EventId == model.EventId);
if (registration is null)
{
return NotFound();
}
registration.PersonId = model.PersonId;
registration.SportId = model.SportId;
await ctx.SaveChangesAsync();
var rowModel = await ctx.Registrations
.AsNoTracking()
.Where(r => r.Id == id)
.Select(r => new RegistrationViewModel
{
Id = r.Id,
EventId = r.EventId,
PersonId = r.PersonId,
SportId = r.SportId,
PersonName = r.Person.FirstName + " " + r.Person.LastName,
PersonTranscription = r.Person.FirstNameTranscription + " " + r.Person.LastNameTranscription,
CountryCode = r.Person.CountryCode,
CountryName = r.Person.CountryCodeNavigation.Name,
SportName = r.Sport.Name,
RegisteredAt = r.RegisteredAt
})
.FirstAsync();
return PartialView("_RegistrationRow", rowModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id, int eventId, SieveModel sieveModel)
{
var registration = await ctx.Registrations.FirstOrDefaultAsync(r => r.Id == id && r.EventId == eventId);
if (registration is null)
{
return NotFound();
}
ctx.Registrations.Remove(registration);
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = "Registration was deleted successfully."
}
});
var viewModel = await BuildPageViewModelAsync(eventId, sieveModel);
return PartialView("_RegistrationsPanel", viewModel);
}
private async Task<RegistrationsPageViewModel> BuildPageViewModelAsync(int selectedEventId, SieveModel sieveModel, List<SelectListItem>? eventOptions = null)
{
sieveModel.SetDefaultPagingAndSorting(pagingSettings.PageSize, "RegisteredAt");
var normalizedFilters = sieveModel.Filters?.Trim() ?? string.Empty;
var nameFilter = SieveModelExtensions.ExtractFilterValue(normalizedFilters, "PersonTranscription");
var countryFilter = SieveModelExtensions.ExtractFilterValue(normalizedFilters, "CountryCode", "==");
var baseQuery = ctx.Registrations
.AsNoTracking()
.Where(r => r.EventId == selectedEventId)
.Select(r => new RegistrationViewModel
{
Id = r.Id,
EventId = r.EventId,
PersonId = r.PersonId,
SportId = r.SportId,
PersonName = r.Person.FirstName + " " + r.Person.LastName,
PersonTranscription = r.Person.FirstNameTranscription + " " + r.Person.LastNameTranscription,
CountryCode = r.Person.CountryCode,
CountryName = r.Person.CountryCodeNavigation.Name,
SportName = r.Sport.Name,
RegisteredAt = r.RegisteredAt
});
var totalCount = await baseQuery.CountAsync();
var filteredCount = string.IsNullOrWhiteSpace(normalizedFilters)
? totalCount
: await sieveProcessor
.Apply(sieveModel, baseQuery, applyFiltering: true, applySorting: false, applyPagination: false)
.CountAsync();
var pagingInfo = new PagingInfo
{
FilteredItemsCount = filteredCount,
TotalItemsCount = totalCount,
ItemsPerPage = sieveModel.PageSize!.Value,
CurrentPage = sieveModel.Page!.Value,
Sorts = sieveModel.Sorts ?? "RegisteredAt",
Filters = normalizedFilters,
NameFilter = nameFilter
};
if (pagingInfo.CurrentPage > pagingInfo.TotalPages)
{
pagingInfo.CurrentPage = pagingInfo.TotalPages;
sieveModel.Page = pagingInfo.CurrentPage;
}
var registrationsData = await sieveProcessor
.Apply(sieveModel, baseQuery)
.ToListAsync();
var registrations = new PagedList<RegistrationViewModel>(registrationsData, pagingInfo);
eventOptions ??= await GetEventOptionsAsync(selectedEventId);
MarkSelectedEvent(eventOptions, selectedEventId);
var selectedEventName = eventOptions.FirstOrDefault(e => e.Selected)?.Text ?? string.Empty;
var canCreate = await CanCreateRegistrationsAsync();
var countryOptions = await GetCountryOptionsAsync(countryFilter);
var createModel = new RegistrationViewModel
{
EventId = selectedEventId
};
await PopulateRegistrationOptionsAsync(createModel);
return new RegistrationsPageViewModel
{
SelectedEventId = selectedEventId,
SelectedEventName = selectedEventName,
EventOptions = eventOptions,
CountryOptions = countryOptions,
CountryFilter = countryFilter,
Registrations = registrations,
CreateModel = createModel,
CanCreate = canCreate,
CreateDisabledMessage = canCreate ? null : Constants.Messages.RegistrationDependenciesRequired
};
}
private async Task PopulateRegistrationOptionsAsync(RegistrationViewModel model)
{
if (model.PersonId > 0)
{
model.PersonLookup = await ctx.People
.AsNoTracking()
.Where(p => p.Id == model.PersonId)
.Select(p => p.FirstName + " " + p.LastName + " (" + p.FirstNameTranscription + " " + p.LastNameTranscription + ")")
.FirstOrDefaultAsync() ?? string.Empty;
}
else
{
model.PersonLookup = string.Empty;
}
model.SportOptions = await ctx.Sports
.AsNoTracking()
.OrderBy(s => s.Name)
.Select(s => new SelectListItem
{
Value = s.Id.ToString(),
Text = s.Name,
Selected = s.Id == model.SportId
})
.ToListAsync();
}
private async Task<List<SelectListItem>> GetEventOptionsAsync(int? selectedEventId)
{
var events = await ctx.Events
.AsNoTracking()
.OrderBy(e => e.EventDate)
.ThenBy(e => e.Name)
.ToListAsync();
return events
.Select(e => new SelectListItem
{
Value = e.Id.ToString(),
Text = $"{e.Name} ({e.EventDate:dd.MM.yyyy.})",
Selected = e.Id == selectedEventId
})
.ToList();
}
private async Task<bool> CanCreateRegistrationsAsync()
{
return await ctx.Events.AsNoTracking().AnyAsync()
&& await ctx.People.AsNoTracking().AnyAsync()
&& await ctx.Sports.AsNoTracking().AnyAsync();
}
private async Task<List<SelectListItem>> GetCountryOptionsAsync(string? selectedCountryCode)
{
return await ctx.Countries
.AsNoTracking()
.OrderBy(c => c.Name)
.Select(c => new SelectListItem
{
Value = c.Code,
Text = c.Name,
Selected = c.Code == selectedCountryCode
})
.ToListAsync();
}
private static void MarkSelectedEvent(IEnumerable<SelectListItem> events, int selectedEventId)
{
foreach (var eventOption in events)
{
eventOption.Selected = string.Equals(eventOption.Value, selectedEventId.ToString(), StringComparison.Ordinal);
}
}
}

View File

@@ -0,0 +1,228 @@
using System.Text.Json;
#if POSTGRES
using Events.EF.Data.Postgres;
#else
using Events.EF.Data.MSSQL;
#endif
using Events.EF.Models;
using Events.MVC.Models;
using Events.MVC.Models.Sports;
using Events.MVC.Util.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Sieve.Models;
using Sieve.Services;
namespace Events.MVC.Controllers;
public class SportsController : Controller
{
private readonly EventsContext ctx;
private readonly ISieveProcessor sieveProcessor;
private readonly PagingSettings pagingSettings;
public SportsController(EventsContext ctx, ISieveProcessor sieveProcessor, IOptions<PagingSettings> pagingSettings)
{
this.ctx = ctx;
this.sieveProcessor = sieveProcessor;
this.pagingSettings = pagingSettings.Value;
}
public async Task<IActionResult> Index(SieveModel sieveModel)
{
var viewModel = await BuildSportsListAsync(sieveModel);
if (Request.Headers.ContainsKey(Constants.HtmxHeaders.Request))
{
return PartialView("_SportsList", viewModel);
}
return View(viewModel);
}
[HttpGet]
public async Task<IActionResult> Row(int id)
{
var sport = await ctx.Sports
.AsNoTracking()
.FirstOrDefaultAsync(s => s.Id == id);
if (sport is null)
{
return NotFound();
}
return PartialView("_SportRow", new SportViewModel
{
Id = sport.Id,
Name = sport.Name
});
}
[HttpGet]
public async Task<IActionResult> EditRow(int id)
{
var sport = await ctx.Sports
.AsNoTracking()
.FirstOrDefaultAsync(s => s.Id == id);
if (sport is null)
{
return NotFound();
}
return PartialView("_SportEditRow", new SportViewModel
{
Id = sport.Id,
Name = sport.Name
});
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(SportViewModel model, SieveModel sieveModel)
{
if (!ModelState.IsValid)
{
Response.Headers[Constants.HtmxHeaders.Retarget] = "#create-sport-form";
Response.Headers[Constants.HtmxHeaders.Reswap] = Constants.HtmxSwap.OuterHtml;
return PartialView("_CreateSportForm", model);
}
var sport = new Sport
{
Name = model.Name
};
ctx.Sports.Add(sport);
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.SportCreated] = true,
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = $"Sport '{model.Name}' was added successfully."
}
});
var viewModel = await BuildSportsListAsync(sieveModel);
return PartialView("_SportsList", viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, SportViewModel model)
{
if (id != model.Id)
{
return BadRequest();
}
if (!ModelState.IsValid)
{
return PartialView("_SportEditRow", model);
}
var existingSport = await ctx.Sports.FirstOrDefaultAsync(s => s.Id == id);
if (existingSport is null)
{
return NotFound();
}
existingSport.Name = model.Name;
await ctx.SaveChangesAsync();
return PartialView("_SportRow", new SportViewModel
{
Id = existingSport.Id,
Name = existingSport.Name
});
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id, SieveModel sieveModel)
{
var sport = await ctx.Sports
.Include(s => s.Registrations)
.FirstOrDefaultAsync(s => s.Id == id);
if (sport is null)
{
return NotFound();
}
if (sport.Registrations.Count > 0)
{
Response.StatusCode = StatusCodes.Status409Conflict;
return Content("The sport cannot be deleted because registrations exist.");
}
ctx.Sports.Remove(sport);
var deletedName = sport.Name;
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = $"Sport '{deletedName}' was deleted successfully."
}
});
var viewModel = await BuildSportsListAsync(sieveModel);
return PartialView("_SportsList", viewModel);
}
private async Task<PagedList<SportViewModel>> BuildSportsListAsync(SieveModel sieveModel)
{
sieveModel.SetDefaultPagingAndSorting(pagingSettings.PageSize, "Name");
var normalizedFilters = sieveModel.Filters?.Trim() ?? string.Empty;
var nameFilter = SieveModelExtensions.ExtractFilterValue(normalizedFilters, "Name");
var baseQuery = ctx.Sports
.AsNoTracking()
.Select(s => new SportViewModel
{
Id = s.Id,
Name = s.Name
});
var totalCount = await baseQuery.CountAsync();
var filteredCount = string.IsNullOrWhiteSpace(normalizedFilters)
? totalCount
: await sieveProcessor
.Apply(
sieveModel,
baseQuery,
applyFiltering: true,
applySorting: false,
applyPagination: false)
.CountAsync();
var pagingInfo = new PagingInfo
{
FilteredItemsCount = filteredCount,
TotalItemsCount = totalCount,
ItemsPerPage = sieveModel.PageSize!.Value,
CurrentPage = sieveModel.Page!.Value,
Sorts = sieveModel.Sorts ?? "Name",
Filters = normalizedFilters,
NameFilter = nameFilter
};
if (pagingInfo.CurrentPage > pagingInfo.TotalPages)
{
pagingInfo.CurrentPage = pagingInfo.TotalPages;
sieveModel.Page = pagingInfo.CurrentPage;
}
var sports = await sieveProcessor
.Apply(sieveModel, baseQuery)
.ToListAsync();
return new PagedList<SportViewModel>(sports, pagingInfo);
}
}

View File

@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup>
<UserSecretsId>PI</UserSecretsId>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DefineConstants>$(DefineConstants);MSSQL</DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Web.LibraryManager.Build" Version="3.0.71" />
<PackageReference Include="Sieve" Version="2.5.5" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Events.EF\Events.EF.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,14 @@
using System.ComponentModel.DataAnnotations;
namespace Events.MVC.Models.Countries;
public class CountryTranslationViewModel
{
[Display(Name = "Language")]
[StringLength(10)]
public string LanguageCode { get; set; } = string.Empty;
[Display(Name = "Translation")]
[StringLength(200)]
public string Name { get; set; } = string.Empty;
}

View File

@@ -0,0 +1,27 @@
using System.ComponentModel.DataAnnotations;
using Sieve.Attributes;
namespace Events.MVC.Models.Countries;
public class CountryViewModel
{
[Display(Name = "Code")]
[Required]
[StringLength(3, MinimumLength = 2)]
[Sieve(CanSort = true, CanFilter = true)]
public string Code { get; set; } = string.Empty;
[Display(Name = "Alpha-3")]
[Required]
[StringLength(3, MinimumLength = 3)]
[Sieve(CanSort = true, CanFilter = true)]
public string Alpha3 { get; set; } = string.Empty;
[Display(Name = "Name")]
[Required]
[StringLength(100)]
[Sieve(CanSort = true, CanFilter = true)]
public string Name { get; set; } = string.Empty;
public List<CountryTranslationViewModel> Translations { get; set; } = [];
}

View File

@@ -0,0 +1,8 @@
namespace Events.MVC.Models;
public class ErrorViewModel
{
public string? RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}

View File

@@ -0,0 +1,26 @@
using System.ComponentModel.DataAnnotations;
using Sieve.Attributes;
namespace Events.MVC.Models.Events;
public class EventViewModel
{
[Display(Name = "ID")]
[Sieve(CanSort = true)]
public int Id { get; set; }
[Display(Name = "Name")]
[Required]
[StringLength(150)]
[Sieve(CanSort = true, CanFilter = true)]
public string Name { get; set; } = string.Empty;
[Display(Name = "Date")]
[DataType(DataType.Date)]
[Sieve(CanSort = true)]
public DateOnly EventDate { get; set; }
[Display(Name = "Participants")]
[Sieve(CanSort = true)]
public int ParticipantsCount { get; set; }
}

View File

@@ -0,0 +1,3 @@
namespace Events.MVC.Models;
public record PagedList<T>(List<T> Data, PagingInfo PagingInfo);

View File

@@ -0,0 +1,39 @@
namespace Events.MVC.Models;
public class PagingInfo
{
public int TotalItemsCount { get; set; }
public int FilteredItemsCount { get; set; }
public int ItemsPerPage { get; set; }
public int CurrentPage { get; set; }
public string Sorts { get; set; } = "Name";
public string Filters { get; set; } = string.Empty;
public string NameFilter { get; set; } = string.Empty;
public int TotalPages => Math.Max(1, (int)Math.Ceiling((decimal)FilteredItemsCount / ItemsPerPage));
public bool IsFiltered => !string.IsNullOrWhiteSpace(Filters);
public string ToggleSort(string propertyName)
{
return string.Equals(Sorts, propertyName, StringComparison.OrdinalIgnoreCase)
? $"-{propertyName}"
: propertyName;
}
public bool IsSortedBy(string propertyName)
{
return string.Equals(Sorts.TrimStart('-'), propertyName, StringComparison.OrdinalIgnoreCase);
}
public bool IsDescending()
{
return Sorts.StartsWith("-", StringComparison.Ordinal);
}
}

View File

@@ -0,0 +1,10 @@
namespace Events.MVC.Models;
public class PagingSettings
{
public const string SectionName = "Paging";
public int PageSize { get; set; } = 2;
public int PageOffset { get; set; } = 5;
}

View File

@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Events.MVC.Models.People;
public class PeoplePageViewModel
{
public PagedList<PersonViewModel> People { get; set; } = new([], new PagingInfo());
public List<SelectListItem> CountryOptions { get; set; } = [];
public string CountryFilter { get; set; } = string.Empty;
}

View File

@@ -0,0 +1,100 @@
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.Rendering;
using Sieve.Attributes;
namespace Events.MVC.Models.People;
public class PersonViewModel : IValidatableObject
{
[Sieve(CanSort = true)]
public int Id { get; set; }
[Display(Name = "First name")]
[StringLength(100)]
public string? FirstName { get; set; }
[Display(Name = "Last name")]
[StringLength(100)]
public string? LastName { get; set; }
[Display(Name = "First name (transcription)")]
[Required]
[StringLength(100)]
[Sieve(CanSort = true)]
public string FirstNameTranscription { get; set; } = string.Empty;
[Display(Name = "Last name (transcription)")]
[Required]
[StringLength(100)]
[Sieve(CanSort = true)]
public string LastNameTranscription { get; set; } = string.Empty;
[Display(Name = "Address")]
[StringLength(200)]
public string? AddressLine { get; set; }
[Display(Name = "Postal code")]
[StringLength(20)]
public string? PostalCode { get; set; }
[Display(Name = "City")]
[StringLength(100)]
public string? City { get; set; }
[Display(Name = "Address country")]
[StringLength(100)]
public string? AddressCountry { get; set; }
[Display(Name = "E-mail")]
[EmailAddress]
[StringLength(255)]
[Sieve(CanSort = true)]
public string? Email { get; set; }
[Display(Name = "Phone")]
[StringLength(50)]
public string? ContactPhone { get; set; }
[Display(Name = "Birth date")]
[Required]
[Sieve(CanSort = true)]
public DateOnly? BirthDate { get; set; }
[Display(Name = "Document number")]
[Required]
[StringLength(50)]
public string DocumentNumber { get; set; } = string.Empty;
[Display(Name = "Country")]
[Required]
[StringLength(3)]
[Sieve(CanFilter = true)]
public string CountryCode { get; set; } = string.Empty;
[Display(Name = "Full name")]
public string FullName { get; set; } = string.Empty;
[Display(Name = "Full name (transcription)")]
[Sieve(CanFilter = true)]
public string FullNameTranscription { get; set; } = string.Empty;
[Display(Name = "Country")]
[Sieve(CanSort = true)]
public string CountryName { get; set; } = string.Empty;
[Display(Name = "Registrations")]
[Sieve(CanSort = true)]
public int RegistrationsCount { get; set; }
public List<SelectListItem> CountryOptions { get; set; } = [];
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (string.IsNullOrWhiteSpace(Email) && string.IsNullOrWhiteSpace(ContactPhone))
{
yield return new ValidationResult(
Constants.Messages.EmailOrContactPhoneRequired,
new[] { nameof(Email), nameof(ContactPhone) });
}
}
}

View File

@@ -0,0 +1,52 @@
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.Rendering;
using Sieve.Attributes;
namespace Events.MVC.Models.Registrations;
public class RegistrationViewModel
{
[Sieve(CanSort = true)]
public int Id { get; set; }
[Required]
[Range(1, int.MaxValue)]
public int EventId { get; set; }
[Display(Name = "Person")]
[Required]
[Range(1, int.MaxValue)]
public int PersonId { get; set; }
[Display(Name = "Sport")]
[Required]
[Range(1, int.MaxValue)]
public int SportId { get; set; }
[Display(Name = "Person")]
public string PersonLookup { get; set; } = string.Empty;
[Display(Name = "Person")]
[Sieve(CanSort = true, CanFilter = true)]
public string PersonName { get; set; } = string.Empty;
[Display(Name = "Transcription")]
[Sieve(CanFilter = true)]
public string PersonTranscription { get; set; } = string.Empty;
[Display(Name = "Country")]
[Sieve(CanFilter = true)]
public string CountryCode { get; set; } = string.Empty;
public string CountryName { get; set; } = string.Empty;
[Display(Name = "Sport")]
[Sieve(CanSort = true)]
public string SportName { get; set; } = string.Empty;
[Display(Name = "Registered at")]
[Sieve(CanSort = true)]
public DateTime RegisteredAt { get; set; }
public List<SelectListItem> SportOptions { get; set; } = [];
}

View File

@@ -0,0 +1,28 @@
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Events.MVC.Models.Registrations;
public class RegistrationsPageViewModel
{
public int SelectedEventId { get; set; }
public string SelectedEventName { get; set; } = string.Empty;
public List<SelectListItem> EventOptions { get; set; } = [];
public List<SelectListItem> CountryOptions { get; set; } = [];
public string CountryFilter { get; set; } = string.Empty;
public PagedList<RegistrationViewModel> Registrations { get; set; } = new([], new PagingInfo
{
ItemsPerPage = 10,
CurrentPage = 1
});
public RegistrationViewModel CreateModel { get; set; } = new();
public bool CanCreate { get; set; }
public string? CreateDisabledMessage { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System.ComponentModel.DataAnnotations;
using Sieve.Attributes;
namespace Events.MVC.Models.Sports;
public class SportViewModel
{
[Sieve(CanSort = true)]
public int Id { get; set; }
[Display(Name = "Name")]
[Required]
[StringLength(100)]
[Sieve(CanSort = true, CanFilter = true)]
public string Name { get; set; } = string.Empty;
}

View File

@@ -0,0 +1,42 @@
#if POSTGRES
using Events.EF.Data.Postgres;
#else
using Events.EF.Data.MSSQL;
#endif
using Events.EF.Models;
using Events.MVC.Models;
using Events.MVC.Util.Middleware;
using Microsoft.EntityFrameworkCore;
using Sieve.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews(options =>
options.Filters.Add<ProblemDetailsForSqlException>());
#if POSTGRES
builder.Services.AddDbContext<EventsContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("EventsPostgres")));
#else
builder.Services.AddDbContext<EventsContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("EventsMssql")));
#endif
builder.Services.AddScoped<ISieveProcessor, SieveProcessor>();
builder.Services.Configure<PagingSettings>(builder.Configuration.GetSection(PagingSettings.SectionName));
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapDefaultControllerRoute();
app.Run();
public partial class Program;

View File

@@ -0,0 +1,14 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"Events.MVC": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7126;http://localhost:5200",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,28 @@
using System.Text;
namespace Events.MVC.Util.Extensions
{
/// <summary>
/// Class with useful extensions for exceptions handling
/// </summary>
public static class ExceptionExtensions
{
/// <summary>
/// return complete hierarchy of an exception. It checks whether the exception has inner exception,
/// and if it has, then it appends inner exception message.
/// Then it looks for inner exception of the inner exceptions, and so on.
/// </summary>
/// <param name="exc">Exception which message hiearchy should be obtained</param>
/// <returns>String containing all exception hierarchy messages</returns>
public static string CompleteExceptionMessage(this Exception? exc)
{
StringBuilder sb = new();
while (exc != null)
{
sb.AppendLine(exc.Message);
exc = exc.InnerException;
}
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,23 @@
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Text;
namespace Events.MVC.Util.Extensions
{
public static class ModelStateExtensions
{
public static string GetErrorsString(this ModelStateDictionary modelState)
{
StringBuilder sb = new StringBuilder();
foreach (var modelStateEntry in modelState)
{
if (modelStateEntry.Value.Errors.Count > 0)
{
string key = modelStateEntry.Key;
string error = string.Join(", ", modelStateEntry.Value.Errors.Select(e => e.ErrorMessage));
sb.AppendFormat("{0}: {1}; ", key, error);
}
}
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,59 @@
using Sieve.Models;
namespace Events.MVC.Util.Extensions;
public static class SieveModelExtensions
{
public static void SetDefaultPagingAndSorting(this SieveModel sieveModel, int defaultPageSize, string defaultSort)
{
sieveModel.Page ??= 1;
if (sieveModel.Page < 1)
{
sieveModel.Page = 1;
}
if (sieveModel.PageSize is null || sieveModel.PageSize <= 0)
{
sieveModel.PageSize = defaultPageSize;
}
if (string.IsNullOrWhiteSpace(sieveModel.Sorts))
{
sieveModel.Sorts = defaultSort;
}
}
public static string ExtractFilterValue(this SieveModel sieveModel, string propertyName)
{
var filters = sieveModel.Filters?.Trim() ?? string.Empty;
return ExtractFilterValue(filters, propertyName);
}
public static string ExtractFilterValue(string filters, string propertyName)
{
return ExtractFilterValue(filters, propertyName, "@=*", "@=");
}
public static string ExtractFilterValue(string filters, string propertyName, params string[] operators)
{
if (string.IsNullOrWhiteSpace(filters))
{
return string.Empty;
}
foreach (var filter in filters.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
foreach (var filterOperator in operators)
{
var prefix = $"{propertyName}{filterOperator}";
if (filter.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
return filter[prefix.Length..];
}
}
}
return string.Empty;
}
}

View File

@@ -0,0 +1,10 @@
namespace Events.MVC.Util.Extensions;
public static class StringExtensions
{
public static string? TrimToNull(this string? value)
{
var trimmed = value?.Trim();
return string.IsNullOrEmpty(trimmed) ? null : trimmed;
}
}

View File

@@ -0,0 +1,73 @@
using Events.MVC.Util.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using Npgsql;
namespace Events.MVC.Util.Middleware;
public class ProblemDetailsForSqlException : ExceptionFilterAttribute
{
private readonly ILogger<ProblemDetailsForSqlException> logger;
public ProblemDetailsForSqlException(ILogger<ProblemDetailsForSqlException> logger)
{
this.logger = logger;
}
public override void OnException(ExceptionContext context)
{
Exception? exception = context.Exception;
PostgresException? postgresException = null;
while (exception is not null)
{
if (exception is PostgresException currentPostgresException)
{
postgresException = currentPostgresException;
break;
}
if (exception is DbUpdateException dbUpdateException && dbUpdateException.InnerException is not null)
{
exception = dbUpdateException.InnerException;
continue;
}
exception = exception.InnerException;
}
if (postgresException is null)
{
base.OnException(context);
return;
}
ProblemDetails problemDetails = postgresException.SqlState switch
{
PostgresErrorCodes.UniqueViolation => new ProblemDetails
{
Title = "Duplicate data",
Detail = "A record with the same data already exists."
},
PostgresErrorCodes.ForeignKeyViolation => new ProblemDetails
{
Title = "Related data",
Detail = "The operation is not allowed because related data exists."
},
_ => new ProblemDetails
{
Title = "Database error",
Detail = $"An error occurred while saving data to the database. {postgresException.MessageText}"
}
};
logger.LogDebug("Database exception: {message}", context.Exception.CompleteExceptionMessage());
context.ExceptionHandled = true;
context.Result = new ObjectResult(problemDetails)
{
ContentTypes = { "application/problem+json" },
StatusCode = StatusCodes.Status500InternalServerError
};
}
}

View File

@@ -0,0 +1,157 @@
using Events.MVC.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.Extensions.Options;
namespace Events.MVC.Util.TagHelpers;
[HtmlTargetElement("pager", Attributes = "page-info,page-action")]
public class PagerTagHelper : TagHelper
{
private readonly IUrlHelperFactory urlHelperFactory;
private readonly PagingSettings pagingSettings;
public PagerTagHelper(IUrlHelperFactory urlHelperFactory, IOptions<PagingSettings> pagingSettings)
{
this.urlHelperFactory = urlHelperFactory;
this.pagingSettings = pagingSettings.Value;
}
[ViewContext]
[HtmlAttributeNotBound]
public ViewContext ViewContext { get; set; } = null!;
public PagingInfo PageInfo { get; set; } = new();
public string PageAction { get; set; } = string.Empty;
public string PageTitle { get; set; } = "Unesite broj stranice";
public string? PageTarget { get; set; }
public string? PageSwap { get; set; }
public bool PagePushUrl { get; set; }
[HtmlAttributeName(DictionaryAttributePrefix = "page-route-")]
public Dictionary<string, string> PageRouteValues { get; set; } = [];
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "nav";
output.Attributes.SetAttribute("aria-label", "Pager");
var paginationList = new TagBuilder("ul");
paginationList.AddCssClass("pagination");
paginationList.AddCssClass("mb-0");
var firstPageInRange = Math.Max(1, PageInfo.CurrentPage - pagingSettings.PageOffset);
var lastPageInRange = Math.Min(PageInfo.TotalPages, PageInfo.CurrentPage + pagingSettings.PageOffset);
if (firstPageInRange > 1)
{
paginationList.InnerHtml.AppendHtml(BuildListItemForPage(1, "1.."));
}
for (var page = firstPageInRange; page <= lastPageInRange; page++)
{
paginationList.InnerHtml.AppendHtml(
page == PageInfo.CurrentPage
? BuildListItemForCurrentPage(page)
: BuildListItemForPage(page));
}
if (lastPageInRange < PageInfo.TotalPages)
{
paginationList.InnerHtml.AppendHtml(BuildListItemForPage(PageInfo.TotalPages, $"..{PageInfo.TotalPages}"));
}
output.Content.AppendHtml(paginationList);
}
private TagBuilder BuildListItemForPage(int page)
{
return BuildListItemForPage(page, page.ToString());
}
private TagBuilder BuildListItemForPage(int page, string text)
{
var urlHelper = urlHelperFactory.GetUrlHelper(ViewContext);
var url = urlHelper.Action(PageAction, BuildRouteValues(page)) ?? string.Empty;
var anchor = new TagBuilder("a");
anchor.InnerHtml.Append(text);
anchor.Attributes["href"] = url;
anchor.AddCssClass("page-link");
ApplyHtmxAttributes(anchor, url);
var listItem = new TagBuilder("li");
listItem.AddCssClass("page-item");
listItem.InnerHtml.AppendHtml(anchor);
return listItem;
}
private TagBuilder BuildListItemForCurrentPage(int page)
{
var urlHelper = urlHelperFactory.GetUrlHelper(ViewContext);
var urlTemplate = urlHelper.Action(PageAction, BuildRouteValues("__page__")) ?? string.Empty;
var input = new TagBuilder("input");
input.Attributes["type"] = "text";
input.Attributes["value"] = page.ToString();
input.Attributes["data-current"] = page.ToString();
input.Attributes["data-min"] = "1";
input.Attributes["data-max"] = PageInfo.TotalPages.ToString();
input.Attributes["data-url-template"] = urlTemplate;
input.Attributes["title"] = PageTitle;
if (!string.IsNullOrWhiteSpace(PageTarget))
{
input.Attributes["data-target"] = PageTarget;
}
if (!string.IsNullOrWhiteSpace(PageSwap))
{
input.Attributes["data-swap"] = PageSwap;
}
input.Attributes["data-push-url"] = PagePushUrl.ToString().ToLowerInvariant();
input.AddCssClass("page-link");
input.AddCssClass("pagebox");
var listItem = new TagBuilder("li");
listItem.AddCssClass("page-item");
listItem.AddCssClass("active");
listItem.InnerHtml.AppendHtml(input);
return listItem;
}
private void ApplyHtmxAttributes(TagBuilder tagBuilder, string url)
{
if (string.IsNullOrWhiteSpace(PageTarget))
{
return;
}
tagBuilder.Attributes["hx-get"] = url;
tagBuilder.Attributes["hx-target"] = PageTarget;
tagBuilder.Attributes["hx-swap"] = string.IsNullOrWhiteSpace(PageSwap) ? "outerHTML" : PageSwap;
if (PagePushUrl)
{
tagBuilder.Attributes["hx-push-url"] = "true";
}
}
private RouteValueDictionary BuildRouteValues(object pageValue)
{
var routeValues = new RouteValueDictionary(PageRouteValues.ToDictionary(kvp => kvp.Key, kvp => (object?)kvp.Value));
routeValues["page"] = pageValue;
routeValues["pageSize"] = PageInfo.ItemsPerPage;
routeValues["sorts"] = PageInfo.Sorts;
routeValues["filters"] = PageInfo.Filters;
return routeValues;
}
}

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>

View File

@@ -0,0 +1,43 @@
@model PagedList<Events.MVC.Models.Events.EventViewModel>
@{
ViewData[Constants.ViewDataKeys.Title] = "Events";
ViewData[Constants.ViewDataKeys.HeaderActionLabel] = "New event";
ViewData[Constants.ViewDataKeys.HeaderActionTarget] = "#create-event-panel";
}
<div class="d-flex flex-column gap-4">
<section id="create-event-panel" class="collapse">
<div class="card border-0 shadow-sm">
<div class="card-body">
<h2 class="h5 mb-3">Add a new event</h2>
<div id="create-event-form">
<partial name="_CreateEventForm" model='new Events.MVC.Models.Events.EventViewModel { EventDate = DateOnly.FromDateTime(DateTime.Today) }' />
</div>
</div>
</div>
</section>
<partial name="_EventsList" model="Model" />
</div>
@section Scripts {
<script>
document.body.addEventListener(@Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.HtmxEvents.EventCreated)), function () {
var form = document.querySelector("#create-event-form form");
if (form) {
form.reset();
}
var dateInput = document.querySelector("#create-event-form input[type='date']");
if (dateInput && !dateInput.value) {
dateInput.value = new Date().toISOString().split("T")[0];
}
var panel = document.getElementById("create-event-panel");
if (panel && window.bootstrap) {
bootstrap.Collapse.getOrCreateInstance(panel).hide();
}
});
</script>
}

View File

@@ -0,0 +1,26 @@
@model Events.MVC.Models.Events.EventViewModel
<form
asp-action="Create"
method="post"
hx-post="@Url.Action("Create", "Events")"
hx-include="#events-state"
hx-target="#events-list"
hx-swap="outerHTML">
@Html.AntiForgeryToken()
<div class="row g-3 align-items-end">
<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-4 col-lg-3">
<label asp-for="EventDate" class="form-label"></label>
<input asp-for="EventDate" class="form-control" type="date" />
<span asp-validation-for="EventDate" class="text-danger small"></span>
</div>
<div class="col-sm-auto">
<button type="submit" class="btn btn-primary">Add event</button>
</div>
</div>
</form>

View File

@@ -0,0 +1,40 @@
@model Events.MVC.Models.Events.EventViewModel
<tr id="event-@Model.Id">
<td>@Model.Id</td>
<td colspan="4">
<form
asp-action="Edit"
asp-route-id="@Model.Id"
method="post"
hx-post="@Url.Action("Edit", "Events", new { id = Model.Id })"
hx-target="#event-@Model.Id"
hx-swap="outerHTML">
@Html.AntiForgeryToken()
<input asp-for="Id" type="hidden" />
<div class="row g-2 align-items-start">
<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-sm-4 col-lg-3">
<input asp-for="EventDate" class="form-control" type="date" />
<span asp-validation-for="EventDate" 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", "Events", new { id = Model.Id })"
hx-target="#event-@Model.Id"
hx-swap="outerHTML">
Cancel
</button>
</div>
</div>
</form>
</td>
</tr>

View File

@@ -0,0 +1,42 @@
@model Events.MVC.Models.Events.EventViewModel
<tr id="event-@Model.Id">
<td>@Model.Id</td>
<td>@Model.Name</td>
<td>@Model.EventDate.ToString("dd.MM.yyyy.")</td>
<td>@Model.ParticipantsCount</td>
<td class="text-end">
<div class="d-inline-flex gap-2">
<a
asp-controller="Registrations"
asp-action="Index"
asp-route-eventId="@Model.Id"
class="btn btn-sm btn-outline-secondary">
Registrations
</a>
<button
type="button"
class="btn btn-sm btn-outline-primary"
hx-get="@Url.Action("EditRow", "Events", new { id = Model.Id })"
hx-target="#event-@Model.Id"
hx-swap="outerHTML">
Edit
</button>
<form
asp-action="Delete"
asp-route-id="@Model.Id"
method="post"
class="d-inline"
hx-post="@Url.Action("Delete", "Events", new { id = Model.Id })"
hx-include="#events-state"
hx-target="#events-list"
hx-swap="outerHTML"
hx-confirm="Delete event '@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,186 @@
@model PagedList<Events.MVC.Models.Events.EventViewModel>
<section class="card border-0 shadow-sm" id="events-list">
<div class="card-body">
<div id="events-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", "Events")"
hx-target="#events-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">Events 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="eventNameFilter"
value="@Model.PagingInfo.NameFilter"
data-name-filter-input
class="form-control"
style="max-width: 18rem;"
placeholder="Search by event name"
aria-label="Filter by event 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", "Events", new { page = 1, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.Sorts, filters = string.Empty })"
hx-target="#events-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("Id")"
asp-route-filters="@Model.PagingInfo.Filters"
class="link-dark link-underline-opacity-0"
hx-get="@Url.Action("Index", "Events", new { page = Model.PagingInfo.CurrentPage, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.ToggleSort("Id"), filters = Model.PagingInfo.Filters })"
hx-target="#events-list"
hx-swap="outerHTML"
hx-push-url="true">
ID@(Model.PagingInfo.IsSortedBy("Id") ? (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", "Events", new { page = Model.PagingInfo.CurrentPage, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.ToggleSort("Name"), filters = Model.PagingInfo.Filters })"
hx-target="#events-list"
hx-swap="outerHTML"
hx-push-url="true">
Name@(Model.PagingInfo.IsSortedBy("Name") ? (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("EventDate")"
asp-route-filters="@Model.PagingInfo.Filters"
class="link-dark link-underline-opacity-0"
hx-get="@Url.Action("Index", "Events", new { page = Model.PagingInfo.CurrentPage, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.ToggleSort("EventDate"), filters = Model.PagingInfo.Filters })"
hx-target="#events-list"
hx-swap="outerHTML"
hx-push-url="true">
Date@(Model.PagingInfo.IsSortedBy("EventDate") ? (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("ParticipantsCount")"
asp-route-filters="@Model.PagingInfo.Filters"
class="link-dark link-underline-opacity-0"
hx-get="@Url.Action("Index", "Events", new { page = Model.PagingInfo.CurrentPage, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.ToggleSort("ParticipantsCount"), filters = Model.PagingInfo.Filters })"
hx-target="#events-list"
hx-swap="outerHTML"
hx-push-url="true">
Participants@(Model.PagingInfo.IsSortedBy("ParticipantsCount") ? (Model.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th class="text-end"></th>
</tr>
</thead>
<tbody>
@if (Model.Data.Count == 0)
{
<tr>
<td colspan="5" class="text-body-secondary">No events to display.</td>
</tr>
}
else
{
@foreach (var eventItem in Model.Data)
{
<partial name="_EventRow" model="eventItem" />
}
}
</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", "Events")"
hx-target="#events-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="#events-list"
page-swap="outerHTML"
page-push-url="true">
</pager>
</div>
</div>
</section>

View File

@@ -0,0 +1,15 @@
@model Events.MVC.Models.ErrorViewModel
@{
ViewData[Constants.ViewDataKeys.Title] = Constants.ToastTitles.Error;
}
<div class="card border-0 shadow-sm">
<div class="card-body">
<h1 class="h4">An error occurred.</h1>
@if (Model.ShowRequestId)
{
<p class="text-body-secondary mb-0">Request ID: <code>@Model.RequestId</code></p>
}
</div>
</div>

View File

@@ -0,0 +1,10 @@
@{
ViewData[Constants.ViewDataKeys.Title] = "Home";
}
<section class="card border-0 shadow-sm">
<div class="card-body p-4">
<h1 class="h3 mb-3">Events</h1>
<p class="mb-0">This sample demonstrates an ASP.NET Core MVC application for managing sports events, countries, people, and registrations using htmx.</p>
</div>
</section>

View File

@@ -0,0 +1,38 @@
@model Events.MVC.Models.People.PeoplePageViewModel
@{
ViewData[Constants.ViewDataKeys.Title] = "People";
ViewData[Constants.ViewDataKeys.HeaderActionLabel] = "New person";
ViewData[Constants.ViewDataKeys.HeaderActionTarget] = "#create-person-panel";
}
<div class="d-flex flex-column gap-4">
<section id="create-person-panel" class="collapse">
<div class="card border-0 shadow-sm">
<div class="card-body">
<h2 class="h5 mb-3">Add a new person</h2>
<div id="create-person-form">
<partial name="_CreatePersonForm" model='(Events.MVC.Models.People.PersonViewModel)ViewData[Constants.ViewDataKeys.CreatePersonModel]!' />
</div>
</div>
</div>
</section>
<partial name="_PeopleList" model="Model" />
</div>
@section Scripts {
<script>
document.body.addEventListener(@Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.HtmxEvents.PersonCreated)), function () {
var form = document.querySelector("#create-person-form form");
if (form) {
form.reset();
}
var panel = document.getElementById("create-person-panel");
if (panel && window.bootstrap) {
bootstrap.Collapse.getOrCreateInstance(panel).hide();
}
});
</script>
}

View File

@@ -0,0 +1,84 @@
@model Events.MVC.Models.People.PersonViewModel
<form
asp-action="Create"
method="post"
hx-post="@Url.Action("Create", "People")"
hx-include="#people-state"
hx-target="#people-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-md-3">
<label asp-for="FirstName" class="form-label"></label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="LastName" class="form-label"></label>
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="FirstNameTranscription" class="form-label"></label>
<input asp-for="FirstNameTranscription" class="form-control" />
<span asp-validation-for="FirstNameTranscription" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="LastNameTranscription" class="form-label"></label>
<input asp-for="LastNameTranscription" class="form-control" />
<span asp-validation-for="LastNameTranscription" class="text-danger small"></span>
</div>
<div class="col-md-4">
<label asp-for="Email" class="form-label"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="ContactPhone" class="form-label"></label>
<input asp-for="ContactPhone" class="form-control" />
<span asp-validation-for="ContactPhone" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="BirthDate" class="form-label"></label>
<input asp-for="BirthDate" type="date" class="form-control" />
<span asp-validation-for="BirthDate" class="text-danger small"></span>
</div>
<div class="col-md-2">
<label asp-for="CountryCode" class="form-label"></label>
<select asp-for="CountryCode" asp-items="Model.CountryOptions" class="form-select">
<option value="">Select a country</option>
</select>
<span asp-validation-for="CountryCode" class="text-danger small"></span>
</div>
<div class="col-md-4">
<label asp-for="DocumentNumber" class="form-label"></label>
<input asp-for="DocumentNumber" class="form-control" />
<span asp-validation-for="DocumentNumber" class="text-danger small"></span>
</div>
<div class="col-md-4">
<label asp-for="AddressLine" class="form-label"></label>
<input asp-for="AddressLine" class="form-control" />
<span asp-validation-for="AddressLine" class="text-danger small"></span>
</div>
<div class="col-md-2">
<label asp-for="PostalCode" class="form-label"></label>
<input asp-for="PostalCode" class="form-control" />
<span asp-validation-for="PostalCode" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="City" class="form-label"></label>
<input asp-for="City" class="form-control" />
<span asp-validation-for="City" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="AddressCountry" class="form-label"></label>
<input asp-for="AddressCountry" class="form-control" />
<span asp-validation-for="AddressCountry" class="text-danger small"></span>
</div>
<div class="col-sm-auto">
<button type="submit" class="btn btn-primary">Add person</button>
</div>
</div>
</form>

View File

@@ -0,0 +1,150 @@
@model Events.MVC.Models.People.PeoplePageViewModel
<section class="card border-0 shadow-sm" id="people-list">
<div class="card-body">
<div id="people-state" class="d-none">
<input type="hidden" name="page" value="@Model.People.PagingInfo.CurrentPage" />
<input type="hidden" name="pageSize" value="@Model.People.PagingInfo.ItemsPerPage" />
<input type="hidden" name="sorts" value="@Model.People.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.People.PagingInfo.Filters" />
<input type="hidden" name="countryFilter" value="@Model.CountryFilter" />
</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", "People")"
hx-target="#people-list"
hx-swap="outerHTML"
hx-push-url="true"
onsubmit="var input=this.querySelector('[data-name-filter-input]'); var country=this.querySelector('[name=countryFilter]'); var filters=this.querySelector('[name=filters]'); var values=[]; if (input && input.value.trim()) { values.push('FullNameTranscription' + String.fromCharCode(64) + '=*' + input.value.trim()); } if (country && country.value) { values.push('CountryCode==' + country.value); } filters.value=values.join(','); this.querySelector('[name=page]').value='1';">
<input type="hidden" name="page" value="1" />
<input type="hidden" name="pageSize" value="@Model.People.PagingInfo.ItemsPerPage" />
<input type="hidden" name="sorts" value="@Model.People.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.People.PagingInfo.Filters" />
<div class="d-flex align-items-center gap-3 pt-2">
<h2 class="h5 mb-0">People list</h2>
<span class="badge text-bg-light">@(Model.People.PagingInfo.IsFiltered ? $"{Model.People.PagingInfo.FilteredItemsCount} / {Model.People.PagingInfo.TotalItemsCount}" : Model.People.PagingInfo.TotalItemsCount.ToString())</span>
</div>
<div class="d-flex align-items-center gap-2 flex-nowrap ms-auto">
<input
id="personNameFilter"
value="@Model.People.PagingInfo.NameFilter"
data-name-filter-input
class="form-control"
style="max-width: 18rem;"
placeholder="Search by transcribed full name"
aria-label="Filter by transcribed full name" />
<select name="countryFilter" asp-items="Model.CountryOptions" class="form-select" style="max-width: 14rem;" aria-label="Filter by country">
<option value="">All countries</option>
</select>
<button type="submit" class="btn btn-outline-primary">Filter</button>
@if (Model.People.PagingInfo.IsFiltered)
{
<a
asp-action="Index"
asp-route-page="1"
asp-route-pageSize="@Model.People.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.People.PagingInfo.Sorts"
asp-route-filters=""
class="btn btn-outline-secondary"
hx-get="@Url.Action("Index", "People", new { page = 1, pageSize = Model.People.PagingInfo.ItemsPerPage, sorts = Model.People.PagingInfo.Sorts, filters = string.Empty })"
hx-target="#people-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.People.PagingInfo.CurrentPage" asp-route-pageSize="@Model.People.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.People.PagingInfo.ToggleSort("Id")" asp-route-filters="@Model.People.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "People", new { page = Model.People.PagingInfo.CurrentPage, pageSize = Model.People.PagingInfo.ItemsPerPage, sorts = Model.People.PagingInfo.ToggleSort("Id"), filters = Model.People.PagingInfo.Filters })" hx-target="#people-list" hx-swap="outerHTML" hx-push-url="true">
ID@(Model.People.PagingInfo.IsSortedBy("Id") ? (Model.People.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>
<a asp-action="Index" asp-route-page="@Model.People.PagingInfo.CurrentPage" asp-route-pageSize="@Model.People.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.People.PagingInfo.ToggleSort("FirstNameTranscription")" asp-route-filters="@Model.People.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "People", new { page = Model.People.PagingInfo.CurrentPage, pageSize = Model.People.PagingInfo.ItemsPerPage, sorts = Model.People.PagingInfo.ToggleSort("FirstNameTranscription"), filters = Model.People.PagingInfo.Filters })" hx-target="#people-list" hx-swap="outerHTML" hx-push-url="true">
First name@(Model.People.PagingInfo.IsSortedBy("FirstNameTranscription") ? (Model.People.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>
<a asp-action="Index" asp-route-page="@Model.People.PagingInfo.CurrentPage" asp-route-pageSize="@Model.People.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.People.PagingInfo.ToggleSort("LastNameTranscription")" asp-route-filters="@Model.People.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "People", new { page = Model.People.PagingInfo.CurrentPage, pageSize = Model.People.PagingInfo.ItemsPerPage, sorts = Model.People.PagingInfo.ToggleSort("LastNameTranscription"), filters = Model.People.PagingInfo.Filters })" hx-target="#people-list" hx-swap="outerHTML" hx-push-url="true">
Last name@(Model.People.PagingInfo.IsSortedBy("LastNameTranscription") ? (Model.People.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th></th>
<th>
<a asp-action="Index" asp-route-page="@Model.People.PagingInfo.CurrentPage" asp-route-pageSize="@Model.People.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.People.PagingInfo.ToggleSort("BirthDate")" asp-route-filters="@Model.People.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "People", new { page = Model.People.PagingInfo.CurrentPage, pageSize = Model.People.PagingInfo.ItemsPerPage, sorts = Model.People.PagingInfo.ToggleSort("BirthDate"), filters = Model.People.PagingInfo.Filters })" hx-target="#people-list" hx-swap="outerHTML" hx-push-url="true">
Birth date@(Model.People.PagingInfo.IsSortedBy("BirthDate") ? (Model.People.PagingInfo.IsDescending() ? " v" : " ^") : "")
</a>
</th>
<th>
<a asp-action="Index" asp-route-page="@Model.People.PagingInfo.CurrentPage" asp-route-pageSize="@Model.People.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.People.PagingInfo.ToggleSort("CountryName")" asp-route-filters="@Model.People.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "People", new { page = Model.People.PagingInfo.CurrentPage, pageSize = Model.People.PagingInfo.ItemsPerPage, sorts = Model.People.PagingInfo.ToggleSort("CountryName"), filters = Model.People.PagingInfo.Filters })" hx-target="#people-list" hx-swap="outerHTML" hx-push-url="true">
Country@(Model.People.PagingInfo.IsSortedBy("CountryName") ? (Model.People.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>
<a asp-action="Index" asp-route-page="@Model.People.PagingInfo.CurrentPage" asp-route-pageSize="@Model.People.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.People.PagingInfo.ToggleSort("RegistrationsCount")" asp-route-filters="@Model.People.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "People", new { page = Model.People.PagingInfo.CurrentPage, pageSize = Model.People.PagingInfo.ItemsPerPage, sorts = Model.People.PagingInfo.ToggleSort("RegistrationsCount"), filters = Model.People.PagingInfo.Filters })" hx-target="#people-list" hx-swap="outerHTML" hx-push-url="true">
Registrations@(Model.People.PagingInfo.IsSortedBy("RegistrationsCount") ? (Model.People.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th class="text-end"></th>
</tr>
</thead>
<tbody>
@if (Model.People.Data.Count == 0)
{
<tr>
<td colspan="8" class="text-body-secondary">No people to display.</td>
</tr>
}
else
{
@foreach (var person in Model.People.Data)
{
<partial name="_PersonRow" model="person" />
}
}
</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.People.PagingInfo.CurrentPage of @Model.People.PagingInfo.TotalPages</small>
<form asp-action="Index" method="get" class="d-inline-flex align-items-center gap-2" hx-get="@Url.Action("Index", "People")" hx-target="#people-list" hx-swap="outerHTML" hx-push-url="true">
<input type="hidden" name="page" value="1" />
<input type="hidden" name="sorts" value="@Model.People.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.People.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.People.PagingInfo.ItemsPerPage == option)">@option</option>
}
</select>
</form>
</div>
<pager
page-info="@Model.People.PagingInfo"
page-action="Index"
page-title="Enter a page number and press Enter"
page-target="#people-list"
page-swap="outerHTML"
page-push-url="true">
</pager>
</div>
</div>
</section>

View File

@@ -0,0 +1,100 @@
@model Events.MVC.Models.People.PersonViewModel
<tr id="person-@Model.Id">
<td>@Model.Id</td>
<td colspan="7">
<form
asp-action="Edit"
asp-route-id="@Model.Id"
method="post"
hx-post="@Url.Action("Edit", "People", new { id = Model.Id })"
hx-target="#person-@Model.Id"
hx-swap="outerHTML">
@Html.AntiForgeryToken()
<input asp-for="Id" 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-md-3">
<label asp-for="FirstName" class="form-label"></label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="LastName" class="form-label"></label>
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="FirstNameTranscription" class="form-label"></label>
<input asp-for="FirstNameTranscription" class="form-control" />
<span asp-validation-for="FirstNameTranscription" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="LastNameTranscription" class="form-label"></label>
<input asp-for="LastNameTranscription" class="form-control" />
<span asp-validation-for="LastNameTranscription" class="text-danger small"></span>
</div>
<div class="col-md-4">
<label asp-for="Email" class="form-label"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="ContactPhone" class="form-label"></label>
<input asp-for="ContactPhone" class="form-control" />
<span asp-validation-for="ContactPhone" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="BirthDate" class="form-label"></label>
<input asp-for="BirthDate" type="date" class="form-control" />
<span asp-validation-for="BirthDate" class="text-danger small"></span>
</div>
<div class="col-md-2">
<label asp-for="CountryCode" class="form-label"></label>
<select asp-for="CountryCode" asp-items="Model.CountryOptions" class="form-select">
<option value="">Select a country</option>
</select>
<span asp-validation-for="CountryCode" class="text-danger small"></span>
</div>
<div class="col-md-4">
<label asp-for="DocumentNumber" class="form-label"></label>
<input asp-for="DocumentNumber" class="form-control" />
<span asp-validation-for="DocumentNumber" class="text-danger small"></span>
</div>
<div class="col-md-4">
<label asp-for="AddressLine" class="form-label"></label>
<input asp-for="AddressLine" class="form-control" />
<span asp-validation-for="AddressLine" class="text-danger small"></span>
</div>
<div class="col-md-2">
<label asp-for="PostalCode" class="form-label"></label>
<input asp-for="PostalCode" class="form-control" />
<span asp-validation-for="PostalCode" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="City" class="form-label"></label>
<input asp-for="City" class="form-control" />
<span asp-validation-for="City" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="AddressCountry" class="form-label"></label>
<input asp-for="AddressCountry" class="form-control" />
<span asp-validation-for="AddressCountry" 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", "People", new { id = Model.Id })"
hx-target="#person-@Model.Id"
hx-swap="outerHTML">
Cancel
</button>
</div>
</div>
</form>
</td>
</tr>

View File

@@ -0,0 +1,37 @@
@model Events.MVC.Models.People.PersonViewModel
<tr id="person-@Model.Id">
<td>@Model.Id</td>
<td>@Model.FirstNameTranscription</td>
<td>@Model.LastNameTranscription</td>
<td>@Model.FullName</td>
<td>@Model.BirthDate?.ToString("dd.MM.yyyy.")</td>
<td>@Model.CountryName</td>
<td>@Model.RegistrationsCount</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", "People", new { id = Model.Id })"
hx-target="#person-@Model.Id"
hx-swap="outerHTML">
Edit
</button>
<form
asp-action="Delete"
asp-route-id="@Model.Id"
method="post"
class="d-inline"
hx-post="@Url.Action("Delete", "People", new { id = Model.Id })"
hx-include="#people-state"
hx-target="#people-list"
hx-swap="outerHTML"
hx-confirm="Delete person '@Model.FullName'?">
@Html.AntiForgeryToken()
<button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
</form>
</div>
</td>
</tr>

View File

@@ -0,0 +1,85 @@
@model Events.MVC.Models.Registrations.RegistrationsPageViewModel
@{
ViewData[Constants.ViewDataKeys.Title] = "Registrations";
ViewData[Constants.ViewDataKeys.HeaderActionLabel] = "New registration";
ViewData[Constants.ViewDataKeys.HeaderActionTarget] = "#create-registration-panel";
}
<partial name="_RegistrationsPanel" model="Model" />
@section Scripts {
<script>
function clearRegistrationSuggestions(scope) {
(scope || document).querySelectorAll(".registration-person-suggestions").forEach(function (container) {
container.innerHTML = "";
});
}
function syncRegistrationPersonLookup(input) {
var form = input.closest("form");
var hiddenInput = form ? form.querySelector("input[name='PersonId']") : null;
if (!hiddenInput) {
return;
}
hiddenInput.value = "";
}
document.body.addEventListener("input", function (event) {
if (event.target.matches("[data-person-autocomplete]")) {
syncRegistrationPersonLookup(event.target);
}
});
document.body.addEventListener("change", function (event) {
if (event.target.matches("[data-person-autocomplete]")) {
syncRegistrationPersonLookup(event.target);
}
});
document.body.addEventListener("click", function (event) {
var suggestion = event.target.closest("[data-person-suggestion]");
if (suggestion) {
var container = suggestion.closest(".registration-person-suggestions");
var wrapper = container ? container.closest(".registration-person-autocomplete") : null;
var input = wrapper ? wrapper.querySelector("[data-person-autocomplete]") : null;
var form = wrapper ? wrapper.closest("form") : null;
var hiddenInput = form ? form.querySelector("input[name='PersonId']") : null;
if (input && hiddenInput) {
input.value = suggestion.dataset.personLabel || "";
hiddenInput.value = suggestion.dataset.personId || "";
}
if (container) {
container.innerHTML = "";
}
return;
}
if (!event.target.closest(".registration-person-autocomplete")) {
clearRegistrationSuggestions(document);
}
});
document.body.addEventListener(@Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.HtmxEvents.RegistrationCreated)), function () {
var form = document.querySelector("#create-registration-form form");
if (form) {
form.reset();
}
var eventInput = document.querySelector("#create-registration-form input[name='EventId']");
var stateEventInput = document.querySelector("#registrations-state input[name='eventId']");
if (eventInput && stateEventInput) {
eventInput.value = stateEventInput.value;
}
clearRegistrationSuggestions(document.getElementById("create-registration-form"));
var panel = document.getElementById("create-registration-panel");
if (panel && window.bootstrap) {
bootstrap.Collapse.getOrCreateInstance(panel).hide();
}
});
</script>
}

View File

@@ -0,0 +1,44 @@
@model Events.MVC.Models.Registrations.RegistrationViewModel
<form
asp-action="Create"
method="post"
hx-post="@Url.Action("Create", "Registrations")"
hx-include="#registrations-state"
hx-target="#registrations-panel"
hx-swap="outerHTML">
@Html.AntiForgeryToken()
<input asp-for="EventId" type="hidden" />
<div asp-validation-summary="ModelOnly" class="text-danger small mb-3"></div>
<div class="row g-3 align-items-end">
<div class="col-md-5">
<label asp-for="PersonId" class="form-label"></label>
<input asp-for="PersonId" type="hidden" />
<div class="position-relative registration-person-autocomplete">
<input
asp-for="PersonLookup"
class="form-control"
placeholder="Start typing a person's name"
autocomplete="off"
data-person-autocomplete
hx-get="@Url.Action("PersonSuggestions", "Registrations")"
hx-include="#registrations-state"
hx-trigger="input changed delay:250ms"
hx-target="#registration-person-suggestions-create"
hx-swap="innerHTML" />
<div id="registration-person-suggestions-create" class="list-group registration-person-suggestions"></div>
</div>
<span asp-validation-for="PersonId" class="text-danger small"></span>
</div>
<div class="col-md-5">
<label asp-for="SportId" class="form-label"></label>
<select asp-for="SportId" asp-items="Model.SportOptions" class="form-select">
<option value="">Select a sport</option>
</select>
<span asp-validation-for="SportId" class="text-danger small"></span>
</div>
<div class="col-sm-auto">
<button type="submit" class="btn btn-primary">Add registration</button>
</div>
</div>
</form>

View File

@@ -0,0 +1,23 @@
@model IReadOnlyList<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>
@if (Model.Count > 0)
{
@foreach (var person in Model)
{
var parts = person.Text.Split('|', 2);
var originalName = parts[0];
var transcription = parts.Length > 1 ? parts[1] : string.Empty;
<button
type="button"
class="list-group-item list-group-item-action"
data-person-suggestion
data-person-id="@person.Value"
data-person-label="@originalName (@transcription)">
<span class="d-block">@originalName</span>
@if (!string.IsNullOrWhiteSpace(transcription))
{
<small class="d-block text-body-secondary">@transcription</small>
}
</button>
}
}

View File

@@ -0,0 +1,64 @@
@model Events.MVC.Models.Registrations.RegistrationViewModel
<tr id="registration-@Model.Id">
<td>@Model.Id</td>
<td colspan="5">
<form
asp-action="Edit"
asp-route-id="@Model.Id"
method="post"
hx-post="@Url.Action("Edit", "Registrations", new { id = Model.Id })"
hx-target="#registration-@Model.Id"
hx-swap="outerHTML">
@Html.AntiForgeryToken()
<input asp-for="Id" type="hidden" />
<input asp-for="EventId" 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-md-5">
<label asp-for="PersonId" class="form-label"></label>
<input asp-for="PersonId" type="hidden" />
<div class="position-relative registration-person-autocomplete">
<input
asp-for="PersonLookup"
class="form-control"
placeholder="Start typing a person's name"
autocomplete="off"
data-person-autocomplete
hx-get="@Url.Action("PersonSuggestions", "Registrations")"
hx-include="#registrations-state"
hx-trigger="input changed delay:250ms"
hx-target="#registration-person-suggestions-@Model.Id"
hx-swap="innerHTML" />
<div id="registration-person-suggestions-@Model.Id" class="list-group registration-person-suggestions"></div>
</div>
<span asp-validation-for="PersonId" class="text-danger small"></span>
</div>
<div class="col-md-4">
<label asp-for="SportId" class="form-label"></label>
<select asp-for="SportId" asp-items="Model.SportOptions" class="form-select">
<option value="">Select a sport</option>
</select>
<span asp-validation-for="SportId" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="RegisteredAt" class="form-label"></label>
<input asp-for="RegisteredAt" class="form-control" disabled />
</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", "Registrations", new { id = Model.Id, eventId = Model.EventId })"
hx-target="#registration-@Model.Id"
hx-swap="outerHTML">
Cancel
</button>
</div>
</div>
</form>
</td>
</tr>

View File

@@ -0,0 +1,39 @@
@model Events.MVC.Models.Registrations.RegistrationViewModel
<tr id="registration-@Model.Id">
<td>@Model.Id</td>
<td>
<span class="d-block">@Model.PersonName</span>
<small class="d-block text-body-secondary">@Model.PersonTranscription</small>
</td>
<td>@Model.CountryName</td>
<td>@Model.SportName</td>
<td>@Model.RegisteredAt.ToString("dd.MM.yyyy. HH:mm")</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", "Registrations", new { id = Model.Id, eventId = Model.EventId })"
hx-target="#registration-@Model.Id"
hx-swap="outerHTML">
Edit
</button>
<form
asp-action="Delete"
asp-route-id="@Model.Id"
asp-route-eventId="@Model.EventId"
method="post"
class="d-inline"
hx-post="@Url.Action("Delete", "Registrations", new { id = Model.Id, eventId = Model.EventId })"
hx-include="#registrations-state"
hx-target="#registrations-panel"
hx-swap="outerHTML"
hx-confirm="Delete this registration?">
@Html.AntiForgeryToken()
<button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
</form>
</div>
</td>
</tr>

View File

@@ -0,0 +1,149 @@
@model Events.MVC.Models.Registrations.RegistrationsPageViewModel
<section class="card border-0 shadow-sm" id="registrations-list">
<div class="card-body">
<div id="registrations-state" class="d-none">
<input type="hidden" name="eventId" value="@Model.SelectedEventId" />
<input type="hidden" name="page" value="@Model.Registrations.PagingInfo.CurrentPage" />
<input type="hidden" name="pageSize" value="@Model.Registrations.PagingInfo.ItemsPerPage" />
<input type="hidden" name="sorts" value="@Model.Registrations.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.Registrations.PagingInfo.Filters" />
<input type="hidden" name="countryFilter" value="@Model.CountryFilter" />
</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", "Registrations")"
hx-target="#registrations-panel"
hx-swap="outerHTML"
hx-push-url="true"
onsubmit="var input=this.querySelector('[data-name-filter-input]'); var country=this.querySelector('[name=countryFilter]'); var filters=this.querySelector('[name=filters]'); var values=[]; if (input && input.value.trim()) { values.push('PersonTranscription' + String.fromCharCode(64) + '=*' + input.value.trim()); } if (country && country.value) { values.push('CountryCode==' + country.value); } filters.value=values.join(','); this.querySelector('[name=page]').value='1';">
<input type="hidden" name="eventId" value="@Model.SelectedEventId" />
<input type="hidden" name="page" value="1" />
<input type="hidden" name="pageSize" value="@Model.Registrations.PagingInfo.ItemsPerPage" />
<input type="hidden" name="sorts" value="@Model.Registrations.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.Registrations.PagingInfo.Filters" />
<div class="d-flex align-items-center gap-3 pt-2">
<h2 class="h5 mb-0">Registrations list</h2>
<span class="badge text-bg-light">@(Model.Registrations.PagingInfo.IsFiltered ? $"{Model.Registrations.PagingInfo.FilteredItemsCount} / {Model.Registrations.PagingInfo.TotalItemsCount}" : Model.Registrations.PagingInfo.TotalItemsCount.ToString())</span>
</div>
<div class="d-flex align-items-center gap-2 flex-nowrap ms-auto">
<input
value="@Model.Registrations.PagingInfo.NameFilter"
data-name-filter-input
class="form-control"
style="max-width: 18rem;"
placeholder="Search by transcription"
aria-label="Filter by transcription" />
<select name="countryFilter" asp-items="Model.CountryOptions" class="form-select" style="max-width: 14rem;" aria-label="Filter by country">
<option value="">All countries</option>
</select>
<button type="submit" class="btn btn-outline-primary">Filter</button>
@if (Model.Registrations.PagingInfo.IsFiltered)
{
<a
asp-action="Index"
asp-route-eventId="@Model.SelectedEventId"
asp-route-page="1"
asp-route-pageSize="@Model.Registrations.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.Registrations.PagingInfo.Sorts"
asp-route-filters=""
class="btn btn-outline-secondary"
hx-get="@Url.Action("Index", "Registrations", new { eventId = Model.SelectedEventId, page = 1, pageSize = Model.Registrations.PagingInfo.ItemsPerPage, sorts = Model.Registrations.PagingInfo.Sorts, filters = string.Empty })"
hx-target="#registrations-panel"
hx-swap="outerHTML"
hx-push-url="true">
Clear
</a>
}
</div>
</form>
@if (!Model.CanCreate && !string.IsNullOrWhiteSpace(Model.CreateDisabledMessage))
{
<div class="alert alert-warning mb-4">@Model.CreateDisabledMessage</div>
}
<div class="table-responsive">
<table class="table align-middle mb-0">
<thead>
<tr>
<th>
<a asp-action="Index" asp-route-eventId="@Model.SelectedEventId" asp-route-page="@Model.Registrations.PagingInfo.CurrentPage" asp-route-pageSize="@Model.Registrations.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.Registrations.PagingInfo.ToggleSort("Id")" asp-route-filters="@Model.Registrations.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "Registrations", new { eventId = Model.SelectedEventId, page = Model.Registrations.PagingInfo.CurrentPage, pageSize = Model.Registrations.PagingInfo.ItemsPerPage, sorts = Model.Registrations.PagingInfo.ToggleSort("Id"), filters = Model.Registrations.PagingInfo.Filters })" hx-target="#registrations-panel" hx-swap="outerHTML" hx-push-url="true">
ID@(Model.Registrations.PagingInfo.IsSortedBy("Id") ? (Model.Registrations.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>
<a asp-action="Index" asp-route-eventId="@Model.SelectedEventId" asp-route-page="@Model.Registrations.PagingInfo.CurrentPage" asp-route-pageSize="@Model.Registrations.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.Registrations.PagingInfo.ToggleSort("PersonName")" asp-route-filters="@Model.Registrations.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "Registrations", new { eventId = Model.SelectedEventId, page = Model.Registrations.PagingInfo.CurrentPage, pageSize = Model.Registrations.PagingInfo.ItemsPerPage, sorts = Model.Registrations.PagingInfo.ToggleSort("PersonName"), filters = Model.Registrations.PagingInfo.Filters })" hx-target="#registrations-panel" hx-swap="outerHTML" hx-push-url="true">
Person@(Model.Registrations.PagingInfo.IsSortedBy("PersonName") ? (Model.Registrations.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>Country</th>
<th>
<a asp-action="Index" asp-route-eventId="@Model.SelectedEventId" asp-route-page="@Model.Registrations.PagingInfo.CurrentPage" asp-route-pageSize="@Model.Registrations.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.Registrations.PagingInfo.ToggleSort("SportName")" asp-route-filters="@Model.Registrations.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "Registrations", new { eventId = Model.SelectedEventId, page = Model.Registrations.PagingInfo.CurrentPage, pageSize = Model.Registrations.PagingInfo.ItemsPerPage, sorts = Model.Registrations.PagingInfo.ToggleSort("SportName"), filters = Model.Registrations.PagingInfo.Filters })" hx-target="#registrations-panel" hx-swap="outerHTML" hx-push-url="true">
Sport@(Model.Registrations.PagingInfo.IsSortedBy("SportName") ? (Model.Registrations.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>
<a asp-action="Index" asp-route-eventId="@Model.SelectedEventId" asp-route-page="@Model.Registrations.PagingInfo.CurrentPage" asp-route-pageSize="@Model.Registrations.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.Registrations.PagingInfo.ToggleSort("RegisteredAt")" asp-route-filters="@Model.Registrations.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "Registrations", new { eventId = Model.SelectedEventId, page = Model.Registrations.PagingInfo.CurrentPage, pageSize = Model.Registrations.PagingInfo.ItemsPerPage, sorts = Model.Registrations.PagingInfo.ToggleSort("RegisteredAt"), filters = Model.Registrations.PagingInfo.Filters })" hx-target="#registrations-panel" hx-swap="outerHTML" hx-push-url="true">
Registered at@(Model.Registrations.PagingInfo.IsSortedBy("RegisteredAt") ? (Model.Registrations.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th class="text-end"></th>
</tr>
</thead>
<tbody>
@if (Model.Registrations.Data.Count == 0)
{
<tr>
<td colspan="6" class="text-body-secondary">No registrations to display.</td>
</tr>
}
else
{
@foreach (var registration in Model.Registrations.Data)
{
<partial name="_RegistrationRow" model="registration" />
}
}
</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.Registrations.PagingInfo.CurrentPage of @Model.Registrations.PagingInfo.TotalPages</small>
<form asp-action="Index" method="get" class="d-inline-flex align-items-center gap-2" hx-get="@Url.Action("Index", "Registrations")" hx-target="#registrations-panel" hx-swap="outerHTML" hx-push-url="true">
<input type="hidden" name="eventId" value="@Model.SelectedEventId" />
<input type="hidden" name="page" value="1" />
<input type="hidden" name="sorts" value="@Model.Registrations.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.Registrations.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.Registrations.PagingInfo.ItemsPerPage == option)">@option</option>
}
</select>
</form>
</div>
<pager
page-info="@Model.Registrations.PagingInfo"
page-action="Index"
page-title="Enter a page number and press Enter"
page-target="#registrations-panel"
page-swap="outerHTML"
page-push-url="true"
page-route-event-id="@Model.SelectedEventId.ToString()">
</pager>
</div>
</div>
</section>

View File

@@ -0,0 +1,43 @@
@model Events.MVC.Models.Registrations.RegistrationsPageViewModel
<div class="d-flex flex-column gap-4" id="registrations-panel">
<section class="card border-0 shadow-sm">
<div class="card-body">
<form
asp-action="Index"
method="get"
class="row g-3 align-items-end"
hx-get="@Url.Action("Index", "Registrations")"
hx-target="#registrations-panel"
hx-swap="outerHTML"
hx-push-url="true">
<div class="col-lg-6">
<label for="selectedEventId" class="form-label">Event</label>
<select
id="selectedEventId"
name="eventId"
asp-items="Model.EventOptions"
class="form-select"
onchange="this.form.requestSubmit()">
</select>
</div>
<div class="col-auto">
<span class="badge text-bg-light">Registrations for: @Model.SelectedEventName</span>
</div>
</form>
</div>
</section>
<section id="create-registration-panel" class="collapse">
<div class="card border-0 shadow-sm">
<div class="card-body">
<h2 class="h5 mb-3">Add a new registration</h2>
<div id="create-registration-form">
<partial name="_CreateRegistrationForm" model="Model.CreateModel" />
</div>
</div>
</div>
</section>
<partial name="_RegistrationsList" model="Model" />
</div>

View File

@@ -0,0 +1,157 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData[Constants.ViewDataKeys.Title] - Events</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
</head>
<body class="bg-body-tertiary">
<header class="border-bottom bg-white shadow-sm">
<nav class="navbar navbar-expand-lg">
<div class="container">
<a class="navbar-brand fw-semibold" asp-controller="Home" asp-action="Index">Events</a>
@if (ViewData[Constants.ViewDataKeys.HeaderActionLabel] is string headerActionLabel && ViewData[Constants.ViewDataKeys.HeaderActionTarget] is string headerActionTarget)
{
<div class="ms-3 d-none d-lg-flex align-items-center">
<button
type="button"
class="btn btn-sm btn-outline-primary"
data-bs-toggle="collapse"
data-bs-target="@headerActionTarget"
aria-expanded="false"
aria-controls="@headerActionTarget.TrimStart('#')">
@headerActionLabel
</button>
</div>
}
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#mainNav" aria-controls="mainNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="mainNav">
@if (ViewData[Constants.ViewDataKeys.HeaderActionLabel] is string mobileHeaderActionLabel && ViewData[Constants.ViewDataKeys.HeaderActionTarget] is string mobileHeaderActionTarget)
{
<div class="d-lg-none mb-3">
<button
type="button"
class="btn btn-sm btn-outline-primary"
data-bs-toggle="collapse"
data-bs-target="@mobileHeaderActionTarget"
aria-expanded="false"
aria-controls="@mobileHeaderActionTarget.TrimStart('#')">
@mobileHeaderActionLabel
</button>
</div>
}
<ul class="navbar-nav ms-auto gap-lg-2">
<li class="nav-item">
<a class="nav-link" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" asp-controller="Events" asp-action="Index">Events</a>
</li>
<li class="nav-item">
<a class="nav-link" asp-controller="Sports" asp-action="Index">Sports</a>
</li>
<li class="nav-item">
<a class="nav-link" asp-controller="Countries" asp-action="Index">Countries</a>
</li>
<li class="nav-item">
<a class="nav-link" asp-controller="People" asp-action="Index">People</a>
</li>
<li class="nav-item">
<a class="nav-link" asp-controller="Registrations" asp-action="Index">Registrations</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<main class="container py-4">
@RenderBody()
</main>
<div class="toast-container position-fixed bottom-0 end-0 p-3">
<div id="app-toast" class="toast border-0 shadow-sm text-white" role="status" aria-live="polite" aria-atomic="true">
<div id="app-toast-header" class="toast-header">
<strong id="app-toast-title" class="me-auto">Notification</strong>
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
<div id="app-toast-body" class="toast-body"></div>
</div>
</div>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/lib/htmx.org/dist/htmx.min.js"></script>
<script src="~/js/pager.js" asp-append-version="true"></script>
<script>
var toastVariantSuccess = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.ToastVariants.Success));
var toastVariantError = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.ToastVariants.Error));
var toastTitleNotification = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.ToastTitles.Notification));
var toastTitleError = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.ToastTitles.Error));
function showAppToast(options) {
var toastElement = document.getElementById("app-toast");
var headerElement = document.getElementById("app-toast-header");
var titleElement = document.getElementById("app-toast-title");
var bodyElement = document.getElementById("app-toast-body");
if (!toastElement || !headerElement || !titleElement || !bodyElement || !window.bootstrap) {
return;
}
var variant = options.variant || toastVariantSuccess;
toastElement.classList.remove("toast-success", "toast-error");
toastElement.classList.add(variant === toastVariantError ? "toast-error" : "toast-success");
headerElement.classList.remove("text-bg-success", "text-bg-danger");
headerElement.classList.add(variant === toastVariantError ? "text-bg-danger" : "text-bg-success");
titleElement.textContent = options.title || toastTitleNotification;
bodyElement.textContent = options.message || "";
var toast = bootstrap.Toast.getOrCreateInstance(toastElement, { delay: 2500 });
toast.show();
}
document.body.addEventListener(@Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.HtmxEvents.ShowToast)), function (event) {
showAppToast(event.detail || {});
});
document.body.addEventListener("htmx:responseError", function (event) {
var xhr = event.detail.xhr;
var message = "An error occurred while processing the request.";
if (xhr && xhr.responseText) {
try {
var problem = JSON.parse(xhr.responseText);
message = problem.detail || problem.title || xhr.responseText;
}
catch {
message = xhr.responseText;
}
}
showAppToast({
variant: toastVariantError,
title: toastTitleError,
message: message
});
});
@if (TempData[Constants.TempDataKeys.ToastMessage] is string toastMessage)
{
var initialToastJson = System.Text.Json.JsonSerializer.Serialize(new
{
variant = TempData[Constants.TempDataKeys.ToastVariant] as string ?? Constants.ToastVariants.Success,
title = TempData[Constants.TempDataKeys.ToastTitle] as string ?? Constants.ToastTitles.Notification,
message = toastMessage
});
@:showAppToast(@Html.Raw(initialToastJson));
}
</script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>

View File

@@ -0,0 +1,38 @@
@model PagedList<Events.MVC.Models.Sports.SportViewModel>
@{
ViewData[Constants.ViewDataKeys.Title] = "Sports";
ViewData[Constants.ViewDataKeys.HeaderActionLabel] = "New sport";
ViewData[Constants.ViewDataKeys.HeaderActionTarget] = "#create-sport-panel";
}
<div class="d-flex flex-column gap-4">
<section id="create-sport-panel" class="collapse">
<div class="card border-0 shadow-sm">
<div class="card-body">
<h2 class="h5 mb-3">Add a new sport</h2>
<div id="create-sport-form">
<partial name="_CreateSportForm" model='new Events.MVC.Models.Sports.SportViewModel()' />
</div>
</div>
</div>
</section>
<partial name="_SportsList" model="Model" />
</div>
@section Scripts {
<script>
document.body.addEventListener(@Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.HtmxEvents.SportCreated)), function () {
var form = document.querySelector("#create-sport-form form");
if (form) {
form.reset();
}
var panel = document.getElementById("create-sport-panel");
if (panel && window.bootstrap) {
bootstrap.Collapse.getOrCreateInstance(panel).hide();
}
});
</script>
}

View File

@@ -0,0 +1,21 @@
@model Events.MVC.Models.Sports.SportViewModel
<form
asp-action="Create"
method="post"
hx-post="@Url.Action("Create", "Sports")"
hx-include="#sports-state"
hx-target="#sports-list"
hx-swap="outerHTML">
@Html.AntiForgeryToken()
<div class="row g-3 align-items-end">
<div class="col-sm-8 col-lg-6">
<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 sport</button>
</div>
</div>
</form>

View File

@@ -0,0 +1,36 @@
@model Events.MVC.Models.Sports.SportViewModel
<tr id="sport-@Model.Id">
<td>@Model.Id</td>
<td colspan="2">
<form
asp-action="Edit"
asp-route-id="@Model.Id"
method="post"
hx-post="@Url.Action("Edit", "Sports", new { id = Model.Id })"
hx-target="#sport-@Model.Id"
hx-swap="outerHTML">
@Html.AntiForgeryToken()
<input asp-for="Id" type="hidden" />
<div class="row g-2 align-items-start">
<div class="col-lg-6">
<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", "Sports", new { id = Model.Id })"
hx-target="#sport-@Model.Id"
hx-swap="outerHTML">
Cancel
</button>
</div>
</div>
</form>
</td>
</tr>

View File

@@ -0,0 +1,32 @@
@model Events.MVC.Models.Sports.SportViewModel
<tr id="sport-@Model.Id">
<td>@Model.Id</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", "Sports", new { id = Model.Id })"
hx-target="#sport-@Model.Id"
hx-swap="outerHTML">
Edit
</button>
<form
asp-action="Delete"
asp-route-id="@Model.Id"
method="post"
class="d-inline"
hx-post="@Url.Action("Delete", "Sports", new { id = Model.Id })"
hx-include="#sports-state"
hx-target="#sports-list"
hx-swap="outerHTML"
hx-confirm="Delete sport '@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,156 @@
@model PagedList<Events.MVC.Models.Sports.SportViewModel>
<section class="card border-0 shadow-sm" id="sports-list">
<div class="card-body">
<div id="sports-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", "Sports")"
hx-target="#sports-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">Sports 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="nameFilter"
value="@Model.PagingInfo.NameFilter"
data-name-filter-input
class="form-control"
style="max-width: 18rem;"
placeholder="Search by sport name"
aria-label="Filter by sport 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", "Sports", new { page = 1, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.Sorts, filters = string.Empty })"
hx-target="#sports-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("Id")"
asp-route-filters="@Model.PagingInfo.Filters"
class="link-dark link-underline-opacity-0"
hx-get="@Url.Action("Index", "Sports", new { page = Model.PagingInfo.CurrentPage, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.ToggleSort("Id"), filters = Model.PagingInfo.Filters })"
hx-target="#sports-list"
hx-swap="outerHTML"
hx-push-url="true">
ID@(Model.PagingInfo.IsSortedBy("Id") ? (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", "Sports", new { page = Model.PagingInfo.CurrentPage, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.ToggleSort("Name"), filters = Model.PagingInfo.Filters })"
hx-target="#sports-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 id="sports-table-body">
@if (Model.Data.Count == 0)
{
<tr>
<td colspan="3" class="text-body-secondary">No sports to display.</td>
</tr>
}
else
{
@foreach (var sport in Model.Data)
{
<partial name="_SportRow" model="sport" />
}
}
</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", "Sports")"
hx-target="#sports-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="#sports-list"
page-swap="outerHTML"
page-push-url="true">
</pager>
</div>
</div>
</section>

View File

@@ -0,0 +1,5 @@
@using Events.EF.Models
@using Events.MVC
@using Events.MVC.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Events.MVC

View File

@@ -0,0 +1,3 @@
@{
Layout = "_Layout";
}

View File

@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@@ -0,0 +1,17 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Paging": {
"PageSize": 10,
"PageOffset": 5
},
"ConnectionStrings": {
"EventsMssql": "Data Source=.,1433;Initial Catalog=Events;User Id=sport;Password=go and look in the secrets file;TrustServerCertificate=True",
"EventsPostgres": "Host=localhost;Port=5432;Database=events;Username=sport;Password=go and look in the secrets file;Persist Security Info=True;"
}
}

View File

@@ -0,0 +1,21 @@
{
"version": "1.0",
"defaultProvider": "jsdelivr",
"libraries": [
{
"library": "bootstrap@5.3.3",
"destination": "wwwroot/lib/bootstrap/",
"files": [
"dist/css/bootstrap.min.css",
"dist/js/bootstrap.bundle.min.js"
]
},
{
"library": "htmx.org@2.0.4",
"destination": "wwwroot/lib/htmx.org/",
"files": [
"dist/htmx.min.js"
]
}
]
}

View File

@@ -0,0 +1,55 @@
body {
min-height: 100vh;
}
.navbar-brand {
letter-spacing: 0.02em;
}
.card {
border-radius: 1rem;
}
.table > :not(caption) > * > * {
padding-top: 0.9rem;
padding-bottom: 0.9rem;
}
.pagebox {
width: 3.5rem;
min-width: 3.5rem;
padding-left: 0.4rem;
padding-right: 0.4rem;
text-align: center;
}
#app-toast {
min-width: 18rem;
}
#app-toast.toast-success {
background-color: #198754;
}
#app-toast.toast-error {
background-color: #dc3545;
}
#app-toast .toast-body {
color: #fff;
}
#app-toast .btn-close {
filter: invert(1);
}
.registration-person-suggestions {
position: absolute;
top: calc(100% + 0.25rem);
left: 0;
right: 0;
z-index: 1050;
max-height: 16rem;
overflow-y: auto;
}

View File

@@ -0,0 +1,61 @@
(function () {
function validRange(value, min, max) {
if (!/^\d+$/.test(value)) {
return false;
}
var page = parseInt(value, 10);
return page >= min && page <= max;
}
function goToPage(input) {
var value = input.value.trim();
var min = parseInt(input.dataset.min, 10);
var max = parseInt(input.dataset.max, 10);
if (!validRange(value, min, max)) {
input.value = input.dataset.current || "";
return;
}
var url = (input.dataset.urlTemplate || "").replace("__page__", value);
if (!url) {
return;
}
var target = input.dataset.target;
var swap = input.dataset.swap || "outerHTML";
var pushUrl = input.dataset.pushUrl === "true";
if (window.htmx && target) {
htmx.ajax("GET", url, {
target: target,
swap: swap,
pushUrl: pushUrl
});
return;
}
window.location.href = url;
}
document.addEventListener("focusin", function (event) {
if (event.target.matches(".pagebox")) {
event.target.select();
}
});
document.addEventListener("keydown", function (event) {
if (!event.target.matches(".pagebox")) {
return;
}
if (event.key === "Enter") {
event.preventDefault();
goToPage(event.target);
}
else if (event.key === "Escape") {
event.target.value = event.target.dataset.current || "";
}
});
})();