.NET Core Blazor App: How to pass data between pages?
I personally prefer to add query string to the url.
For example when I want to pre-select tab when page is loaded:
Call the url like http://localhost:5000/profile?TabIndex=2
In your code you can parse this using NavigationManager and QueryHelpers
Add using Microsoft.AspNetCore.WebUtilities;
Then override one of the lifecycle methods and parse the query parameter
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
Uri uri = this.Nav.ToAbsoluteUri(this.Nav.Uri);
if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("TabIndex", out StringValues values))
{
if (values.SafeAny())
{
_ = int.TryParse(values.First(), out int index);
this.TabIndex = index;
}
}
}
}
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