Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect to a different route in Blazor Server-side

In Blazor Client a redirection can be achieved using

using Microsoft.AspNetCore.Blazor.Browser.Services;
(...)
BrowserUriHelper.Instance.NavigateTo("/route")

This does however not work in a Blazor Server project, as it generates the following error:

Unable to cast object of type 'Microsoft.AspNetCore.Blazor.Server.Circuits.RemoteJSRuntime' to type 'Microsoft.JSInterop.IJSInProcessRuntime'.

How does a redirect in Blazor-Server look like?

like image 599
mikeyy Avatar asked Jan 04 '19 18:01

mikeyy


People also ask

How do you navigate to another page in Blazor with parameter?

By using Blazor route parameters, you can pass values from one page to another page. Use NavigationManager to pass a value and route the parameter to another page. Follow this example to achieve passing values from one page to another. Get the passed Page1 parameter value in Page2.

How do you find the current route in Blazor?

Inject NavigationManager in razor. Use Uri from NavigationManager to get the current URL.

How do you pass multiple parameters in Blazor?

The easiest way is to use Route parameters instead of QueryString: @page "/navigatetopage/{id:int}/{key}" @code { [Parameter] public int Id{get;set;} [Parameter] public string Key{get;set;} ... }

Should I use Blazor server or Blazor Wasm?

The Blazor Server hosting model offers several benefits: Download size is significantly smaller than a Blazor WebAssembly app, and the app loads much faster. The app takes full advantage of server capabilities, including the use of . NET Core APIs.


2 Answers

If you can trigger on the razor page, you can use the following:

@page "/YourPageName"
@inject NavigationManager NavigationManager

<h1>xxx</h1>
.
.
.


@code {

    void MethodToTriggerUrl()
    {
        NavigationManager.NavigateTo("PageToRedirect");
    }
}
like image 106
Mehmet Taha Meral Avatar answered Sep 17 '22 06:09

Mehmet Taha Meral


After time and time of experimenting, I found out that in server side this is working:

using Microsoft.AspNetCore.Blazor.Services;
(...)
UriHelper.NavigateTo("/route");

Granted, looks almost the same, but does the work (at least in Blazor 0.8)

like image 42
mikeyy Avatar answered Sep 21 '22 06:09

mikeyy