Sharing Code between Razor Pages in Blazor Project

Viewed 557

I have a method in my Razor page, that needs to be used in all my razor pages.

async Task ShowNotification(NotificationMessage message)
{
    notificationService.Notify(message);

    await InvokeAsync(() => { StateHasChanged(); });
}

What is the best practice to be able to share this method between razor pages and not have to put this method in each page?

1 Answers

You can have your pages inherit a base class, and put this method into that base class.

NotifyingPage.cs

public abstract class NotifyingPage : ComponentBase
{
    async Task ShowNotification(NotificationMessage message)
    {
        notificationService.Notify(message);

        await InvokeAsync(() => { StateHasChanged(); });
    }
}

SomeRazorPage.razor

@page "/something"
@inherits NotifyingPage

<div>Whatever</div>
@code {
    protected override async Task OnInitializedAsync()
    {
        await ShowNotification("Initialized!");
    }
}
Related