.NET Core Blazor App: How to pass data between pages?

jorjj picture jorjj · Jul 7, 2018 · Viewed 10.3k times · Source

I just started learning how to make websites with using Blazor template. But I don't know how to pass the data from one page to another. It is a bit different than .NET CORE MVC web application and I couldn't find an example for this.

    <p>Solve This problem: @rnd1 * @rnd2 = ?</p>

    <input type="text" name="result" bind="@result" />
    <input type="button" onclick="@calculate" value="Submit" />

I want to send the value in my textbox to the another page. How can I do this?

Answer

Flores picture Flores · Jul 7, 2018

You can pass it as a parameter.

In the page you want to navigate to, add the parameter to your route:

@page "/navigatetopage/{myvalue}"

and make sure the parameter exists in that page:

[Parameter]
private string myvalue{ get; set; }

In the same page you can pick that up in:

protected override void OnParametersSet()
{
    //the param will be set now
    var test = myvalue;
}

Now in your start page make sure to navigate to the second page including the value:

uriHelper.NavigateTo($"/navigatetopage/{result}");

That uriHelper needs to be injected like this:

@inject Microsoft.AspNetCore.Blazor.Services.IUriHelper uriHelper

UPDATE PREVIEW-9 on preview-9 you should use navigationManager instead of uriHelper, it also has a NavigateTo method

@inject Microsoft.AspNetCore.Components.NavigationManager navigationManager