How do I stop blazor @onclick re-rendering page

Viewed 2166

I am using a blazor sever app

I have a control that when clicked using the @onclick event handler I want to navigate to a new page using the NavigationManager in the click event method. it doesn't really matter what the control is (button, a, tr, etc) they all have the same behavior

if I put a break point in the HTML I can see the current page is re-rendering before it goes to the new page.

a simple way to reproduce this behavior is to make a new blazor project and in the counter.razor page change the code to this

@page "/counter"

<h1>Counter</h1>

@if (1 == 1)
{
<p>Current count: @currentCount</p>
}

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
private void IncrementCount()
    {
        //currentCount++;
    }
}

put a break point on the HTML line "@if (1 == 1)" when the button is clicked it calls the click event which does nothing (code commented out), it then re-renders the page and the break point is hit. The same happens if I add code in the click event calling navigationManager to navigate away from the page, it re-renders before it leaves the page when nothing has changed on the page.

adding onclick:preventDefault and/or @onclick:stopPropagation does not change this

the only thing I have found that does work is adding

    private bool c_blnStopRendering = false;

    protected override bool ShouldRender()
    {
        if (c_blnStopRendering == true) { return false; }
        return base.ShouldRender();
    }

and setting the c_blnStopRendering = true; in the click event but this seems like over kill and very manual to add it everywhere it is needed

2 Answers

I was wondering how you got on with this. I had exactly the same problem (I just wanted to NavigateTo without any re-rendering). Overriding ShouldRender to return false, stopped everything - i.e. it didn't NavigateTo the URL. I was however, Navigating to the same page, but with different parameters in the QS. I seem to have solved the problem, (I think !) when I discovered an optional parameter in the NavigateTo method (public void NavigateTo(string uri, bool forceLoad = false);). I set that to true and it seems to be OK now. Was just interested in your experience

Related