Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing Code between Razor Pages in Blazor Project

Tags:

razor

blazor

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?

like image 283
user2476451 Avatar asked Nov 22 '25 05:11

user2476451


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!");
    }
}
like image 62
Squirrelkiller Avatar answered Nov 24 '25 22:11

Squirrelkiller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!