Introduction
Bootstrap toasts are lightweight notifications that mimic the push notifications popularized by mobile and desktop operating systems.
Learn how to merge C# code into toast to make toast flexible.
Get coding
Toast options for demonstration are read from appsettings.json, while toast options may be hard-coded in code.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ToastOptions": {
"DatabaseError": {
"ToastMessage": "Failed to open database!",
"ToastTitle": "Error",
"ToastDelay": 10000
}
}
}
In the above ToastOptions has DatabaseError item which allows you to have multiple toast configurations.
These classes are used to parse the json above.
public class ToastOptions
{
public ToastMessageOptions DatabaseError { get; set; } = new();
}
public class ToastMessageOptions
{
public string ToastMessage { get; set; } = string.Empty;
public string ToastTitle { get; set; } = string.Empty;
public int ToastDelay { get; set; }
}
Program.cs code using dependency injection to read settings.
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
// Configure ToastOptions using the appsettings.json configuration section
builder.Services.Configure<ToastOptions>(
builder.Configuration.GetSection(nameof(ToastOptions)));
// Register the ReadToastConfiguration service for dependency injection
builder.Services.AddScoped<ReadToastConfiguration>();
var app = builder.Build();
...
Razor page front-end
- The top section is where the business code resides. Here is a button to trigger the toast
- asp-page-handler="ShowToast" relates to the following post event public IActionResult OnPostShowToast()
- The bottom section is the toast which uses model properties to configure the toast
@page
@model IndexModel
@{
ViewData["Title"] = "Bootstrap Toast Demo";
}
<div class="container mt-5">
<h1 class="mb-4 fs-4 text-center">Bootstrap 5 Toast from C#</h1>
<main>
<form method="post" asp-page-handler="ShowToast" class="text-center">
<button type="submit" class="btn btn-danger">
Show error Toast
</button>
</form>
</main>
</div>
@if (!string.IsNullOrWhiteSpace(Model.ToastMessage))
{
<div class="toast-container position-fixed bottom-0 end-0 p-3">
<div id="serverToast"
class="toast text-bg-danger border-0"
role="alert"
aria-live="assertive"
data-bs-delay="@Model.ToastDelay"
aria-atomic="true">
<div class="toast-header">
<span class="me-2">
<img src="images/databasex.svg" alt=""/>
</span>
<strong class="me-auto">@Model.ToastTitle</strong>
<small>@DateTime.Now.ToShortTimeString()</small>
<button type="button"class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
<div class="toast-body">
@Model.ToastMessage
</div>
</div>
</div>
}
@section Scripts {
@if (!string.IsNullOrWhiteSpace(Model.ToastMessage))
{
<script>
document.addEventListener("DOMContentLoaded", function () {
const toastElement = document.getElementById("serverToast");
if (toastElement) {
const toast = new bootstrap.Toast(toastElement, {
autohide: true
});
toast.show();
}
});
</script>
}
}
Razor page back-end
- Primary constructor for ReadToastConfiguration setup in Program.cs
- Post to set toast options
public class IndexModel(ReadToastConfiguration readToast) : PageModel
{
[TempData]
public string? ToastMessage { get; set; }
[TempData]
public string? ToastTitle { get; set; }
[TempData]
public int ToastDelay { get; set; }
public void OnGet()
{
}
public IActionResult OnPostShowToast()
{
var options = readToast.GetToastOptions();
ToastTitle = options.DatabaseError.ToastTitle;
ToastMessage = options.DatabaseError.ToastMessage;
ToastDelay = options.DatabaseError.ToastDelay;
return RedirectToPage();
}
}
Summary
In this article, developers are shown how to create a Bootstrap toast efficiently, with JavaScript needed only to set up one event to show the toast.
See also
- Bootstrap toast documentation
- Using toast notifications in ASP.NET Core Razor Pages
Top comments (0)