DEV Community

Cover image for ASP .NET Core/BS-5 badge
Karen Payne
Karen Payne

Posted on

ASP .NET Core/BS-5 badge

Introduction

Learn how to use the Bootstrap 5 badge component without JavaScript in ASP.NET Core projects.

πŸ’‘ Secret sauce is to treat a badge no different than any other read-only input.

What is a badge

badge sample page

A Bootstrap 5 badge is a small inline label used to highlight counts, statuses, categories, or short pieces of metadata, such as β€œNew,” β€œActive,” or β€œ12.” It is created with the .badge class and usually paired with background utility classes like .bg-primary, .bg-success, or .bg-danger to control its color. Badges scale to match the size of their parent text, making them useful inside headings, buttons, lists, and navigation items. In Bootstrap 5, badges can also be rounded into pill shapes using .rounded-pill, which is commonly used for notification counts or status indicators.

Code walkthrough

In this code sample, appsettings.json reads and writes the value displayed in the badge, whereas in a real application, the badge value may be retrieved from a service.

Source code

Frontend

shows badge configuration

<form method="post">
    <div class="mt-4 mb-2 d-flex gap-3">

        <button type="button" class="btn btn-primary position-relative">
            Inbox
            <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
                @Model.BadgeDisplay
                <span class="visually-hidden">unread messages</span>
            </span>
        </button>

        <button type="submit" asp-page-handler="Increment" class="btn btn-success">
            Increment Badge
        </button>

        <button type="submit" asp-page-handler="Decrement" class="btn btn-secondary">
            Decrement Badge
        </button>

    </div>
</form>
Enter fullscreen mode Exit fullscreen mode

Two buttons are available to simulate incrementing and decrementing the badge value, which both have post events (see below).

Backend

public class BadgeDemoModel : PageModel
{
    public int BadgeCount { get; set; }

    public string BadgeDisplay => BadgeCount > 99 ? "99+" : BadgeCount.ToString();

    public void OnGet()
    {
        BadgeCount = BadgeOperations.BadgeCount();
    }

    public IActionResult OnPostDecrement()
    {
        int currentBadgeCount = BadgeOperations.BadgeCount();

        currentBadgeCount--;

        if (currentBadgeCount < 0)
            currentBadgeCount = 0;

        BadgeOperations.Save(currentBadgeCount);

        return RedirectToPage();
    }
    public IActionResult OnPostIncrement()
    {
        int currentBadgeCount = BadgeOperations.BadgeCount();

        currentBadgeCount++;

        BadgeOperations.Save(currentBadgeCount);

        return RedirectToPage();

    }
}
Enter fullscreen mode Exit fullscreen mode
  • OnPostIncrement increments the badge count and OnPostDecrement decrements the badge count and both save the current

Support class

public class BadgeOperations
{

    public static int BadgeCount()
    {
        var appSettingsPath = AppSettingsPath();

        string json = ReadAllText(appSettingsPath);

        JsonNode? root = JsonNode.Parse(json);

        BadgeSettings? badgeSettings = root?[nameof(BadgeSettings)]?.Deserialize<BadgeSettings>();

        return badgeSettings?.BadgeCount ?? 1;

    }


    public static void Save(int badgeCount)
    {
        var appSettingsPath = AppSettingsPath();

        string json = ReadAllText(appSettingsPath);

        JsonNode? root = JsonNode.Parse(json) ?? new JsonObject();

        var badgeSettings = new BadgeSettings
        {
            BadgeCount = badgeCount
        };

        root[nameof(BadgeSettings)] = JsonSerializer.SerializeToNode(badgeSettings);


        WriteAllText(appSettingsPath, root.ToJsonString(Indented));
    }


    private static string AppSettingsPath()
    {
        return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json"); 
    }

    public static JsonSerializerOptions Indented => new() { WriteIndented = true };
}
Enter fullscreen mode Exit fullscreen mode

Model

public class BadgeSettings
{
    public int BadgeCount { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Summary

The main takeaway from this article is that JavaScript is not always required for backend code to communicate with frontend code.

Top comments (0)