Persist Component State Tag Helper in ASP.NET Core
Prerequisites
Follow the guidance in the Configuration section for either:
Persist state for prerendered components
To persist state for prerendered components, use the Persist Component State Tag Helper (reference source). Add the Tag Helper's tag, <persist-component-state />, inside the closing </body> tag of the _Host page in an app that prerenders components.
Note
Documentation links to .NET reference source usually load the repository's default branch, which represents the product unit's current development for the next release of .NET. To select the branch for a different release, use the Switch branches or tags dropdown list. The ASP.NET Core repository uses a "release/{VERSION}" format for release branch names, where the {VERSION} placeholder is the release version. For example, select the release/6.0 branch for the ASP.NET Core 6.0 release. Other reference source repositories may use different release tag naming schemes.
In Blazor WebAssembly apps (Pages/_Host.cshtml):
<body>
<component type="typeof(App)" render-mode="WebAssemblyPrerendered" />
...
<persist-component-state />
</body>
In Blazor Server apps (Pages/_Host.cshtml):
<body>
<component type="typeof(App)" render-mode="ServerPrerendered" />
...
<persist-component-state />
</body>
Decide what state to persist using the PersistentComponentState service. PersistentComponentState.RegisterOnPersisting registers a callback to persist the component state before the app is paused. The state is retrieved when the application resumes.
In the following example:
- The
{TYPE}placeholder represents the type of data to persist (for example,WeatherForecast[]). - The
{TOKEN}placeholder is a state identifier string (for example,fetchdata).
@implements IDisposable
@inject PersistentComponentState ApplicationState
...
@code {
private {TYPE} data;
private PersistingComponentStateSubscription persistingSubscription;
protected override async Task OnInitializedAsync()
{
persistingSubscription =
ApplicationState.RegisterOnPersisting(PersistData);
if (!ApplicationState.TryTakeFromJson<{TYPE}>(
"{TOKEN}", out var restored))
{
data = await ...;
}
else
{
data = restored!;
}
}
private Task PersistData()
{
ApplicationState.PersistAsJson("{TOKEN}", data);
return Task.CompletedTask;
}
void IDisposable.Dispose()
{
persistingSubscription.Dispose();
}
}
For more information and a complete example, see Prerender and integrate ASP.NET Core Razor components.
Additional resources
Maklum balas
Kirim dan lihat maklum balas untuk