在Blazor中,可以使用Web Storage API(如localStorage或sessionStorage)在客户端存储数据。以下是如何在Blazor中使用localStorage进行客户端存储的简单示例:
_Imports.razor文件中,导入Microsoft.JSInterop命名空间:@using Microsoft.JSInterop
LocalStorageService.cs的新文件,并添加以下代码:using Microsoft.JSInterop;
using System.Threading.Tasks;
public class LocalStorageService
{
private readonly IJSRuntime _jsRuntime;
public LocalStorageService(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime;
}
public async Task SetItemAsync(string key, string value)
{
await _jsRuntime.InvokeVoidAsync("setItem", key, value);
}
public async Task<string> GetItemAsync(string key)
{
return await _jsRuntime.InvokeStringAsync("getItem", key);
}
}
LocalStorageService并调用其方法来存储和检索数据:@inject LocalStorageService LocalStorageService
<button @onclick="SaveData">Save Data</button>
<button @onclick="GetData">Get Data</button>
<p>@data</p>
@code {
private string data;
private async Task SaveData()
{
data = "Hello, Blazor!";
await LocalStorageService.SetItemAsync("myKey", data);
}
private async Task GetData()
{
data = await LocalStorageService.GetItemAsync("myKey");
}
}
在这个示例中,我们创建了一个名为LocalStorageService的类,它提供了SetItemAsync和GetItemAsync方法来存储和检索数据。然后,在Blazor组件中,我们注入了LocalStorageService并调用了这些方法来存储和检索数据。
注意:这个示例使用了JavaScript的localStorage对象。如果你想在Blazor中使用sessionStorage,只需将LocalStorageService类中的_jsRuntime.InvokeVoidAsync("setItem", key, value)和_jsRuntime.InvokeStringAsync("getItem", key)方法中的localStorage替换为sessionStorage即可。