Blazor webassembly ASP.NET Core hosted. How to redirect to page passing data?

726 views Asked by At

I've created a Blazor webassembly ASP.NET Core hosted solution. The solution has three projects: BlazorApp1.Client, BlazorApp1.Server and BlazorApp1.Shared.

In BlazorApp1.Server part, I have a controller with a HttpPost method called MyPost that receives some data.

    [HttpPost]
    [Route("/Register")]
    [Consumes("application/x-www-form-urlencoded")]
    public ActionResult MyPost([FromForm] string data)
    {
        return Ok(data);
    }

I have to redirect to a page called Index that is in BlazorApp1.Client (at http://localhost:48518/Index), passing the data that I've received in the method MyPost.

The problem is how redirect to index passing the data?

How to redirect from MyPost method (in BlazorApp.Server) to an Index page in the BlazorApp.Client?

I look forward to your responses, thanks.

1

There are 1 answers

4
Qiang Fu On

You can use route to pass value to razor component. Change the Index.razor like

@page "/index/{data?}"

<p>@data</p>

@code{
    [Parameter]
    public string? data { get; set; }
}

Then you can pass value by call the URL http://localhost:45818/index/mystring
enter image description here

You can use following code to redirect in a back-end method.

        [HttpPost]
        [Route("/Register")]
        [Consumes("application/x-www-form-urlencoded")]
        public ActionResult MyPost([FromForm] string data)
        {
            return Redirect("http://localhost:45818/index/mystring");
        }

If you redirect from a razor page. inject and use navigationmanager.

@page "/"
@inject NavigationManager navigationManager

<button @onclick=test>Redirect</button>

@code{
    public void test()
    {
        navigationManager.NavigateTo("https://www.google.com");
    }
}