Add onclick event to <a> element in Blazor "prior" to default link handling

Viewed 581

I have a link element that needs to do some custom changes before redirecting to a page. My understanding that "href" and "onclick" can't be used together. The question is then how to organize the link element so it will first calls the event handler and then redirect? Thanks!

1 Answers

Only use onclick and redirect inside the event handler after performing your custom operations.

@inject NavigationManager NavigationManager   

<a @onclick="DoWorkAndRedirect">
    Click me
</a>

@code {
    private void DoWorkAndRedirect(MouseEventArgs e)
    {
        // Do your work here, and then...

        @NavigationManager.NavigateTo("/my-other-page");
    }
}
Related