Search code examples
blazorblazor-client-sideasp.net-blazor

NavigationManager does not works as expected?


If I create a page in Shared - LoginPage.razor :

@inherits LayoutComponentBase

@inject IJSRuntime JSRuntime;
@inject NavigationManager NavigationManager;


<button @onclick="onBtnClick"> sfsdf</button>

@code
{
    public void onBtnClick()
    {
        NavigationManager.NavigateTo( "/Error" );
    }
}

in App.razor change DefaultLayout to the new page above:

<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(LoginPage)" />
    </Found>
    <NotFound>
        <LayoutView Layout="@typeof(LoginPage)">
            <p>Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

Then create a page inside Pages. let say ErrorPage.razor :

@page "/Error"
<h3>ErrorPage</h3>

@code 
{
}

And if I run the app and click the button the page should be changing to Error page, but only the URL is changing.

  • how can I switch to Error page ?

Solution

  • I think, you have missed @Body tag from LoginPage bootstrap component, which will load your error component on button click.

    LoginPage.razor

    @inherits LayoutComponentBase
    @inject NavigationManager navigationManager
    
    <button @onclick="onButtonClick">Go To Error Page</button>
    
    <div class="bodyLoginPage">
        @Body
    </div>
    
    @code{
        public void onButtonClick()
        {
            navigationManager.NavigateTo("/Error");
        }
    }
    

    Hope, it will help. Thanks