How to redirect to a caller in a razor code programmatically?

450 views Asked by At

How can I go to the page caller in razor page code?

I.e. for example: The page Check.razor can be called from several pages. I'd like go back to the caller in the Check.razor code depending on some conditions.

1

There are 1 answers

1
enet On BEST ANSWER

First off, create your Check component with a route parameter, in addition to the usual route template. The first permits navigation to the component without a parameter. The second @page directive takes the {returnurl} route parameter and assigns the value to the ReturnUrl property defined below.

Then add the @inject directive to inject the NavigationManager to your component, so that you can call its NavigateTo method that allows you to navigate to the route passed in the {returnurl} parameter

Check.razor

@page "/check"
@page "/check/{returnurl}"
@inject NavigationManager NavigationManager


<button @onclick="GoBack">Go back</button>

@code {

    [Parameter]
    public string ReturnUrl { get; set; }

    private void GoBack()
    {
       NavigationManager.NavigateTo(ReturnUrl, forceLoad: false);
    }

}

You can now call your Check component from other components. Add the @inject directive to inject the NavigationManager to your component. First, we want to extract the current location; that is where we are: The first line in the CallCheck method does it. Note that if you are in the Counter component and click the "Call Check" button, the variable returnUrl would contain the value "Counter", and if you are in the Index component (of course you need to add the same code as here), the variable returnUrl would contain an empty string.

After extracting the current location, we call the NavigateTo method to navigate to the route contained in the returnUrl variable.

Usage

@inject NavigationManager NavigationManager

<button class="btn btn-primary" @onclick="CallCheck">Call Check</button>


@code 
{
    private void CallCheck()
    {
        var returnUrl = 
              NavigationManager.ToBaseRelativePath(NavigationManager.Uri);


       NavigationManager.NavigateTo($"check/{returnUrl}", forceLoad: false);

    }
}