{"id":36,"date":"2019-09-24T21:02:29","date_gmt":"2019-09-24T11:02:29","guid":{"rendered":"http:\/\/blazortips.azurewebsites.net\/?p=36"},"modified":"2019-09-24T21:16:06","modified_gmt":"2019-09-24T11:16:06","slug":"localstorage-with-blazor","status":"publish","type":"post","link":"https:\/\/blazortips.azurewebsites.net\/localstorage-with-blazor\/","title":{"rendered":"LocalStorage with Blazor"},"content":{"rendered":"\n
how to read and write to local Storage using Blazor <\/p>\n\n\n\n
first we create a LocalStorageService.cs file <\/p>\n\n\n\n
using Microsoft.JSInterop;\nusing System.Threading.Tasks;\n\nnamespace BlazorLocalStorage.Service\n{\n public class LocalStorageService\n {\n private readonly IJSRuntime _js;\n\n public LocalStorageService(IJSRuntime js)\n {\n _js = js;\n }\n\n public async Task<string> GetFromLocalStorage(string key)\n {\n return await _js.InvokeAsync<string>(\"localStorage.getItem\", key);\n }\n\n public async Task SetLocalStorage(string key, string value)\n {\n await _js.InvokeVoidAsync(\"localStorage.setItem\", key, value);\n }\n }\n}<\/code><\/pre>\n\n\n\ninject the service in Startup.cs<\/p>\n\n\n\n
public void ConfigureServices(IServiceCollection services)\n{\n services.AddRazorPages();\n services.AddServerSideBlazor();\n services.AddScoped<LocalStorageService>();\n}<\/code><\/pre>\n\n\n\nCreate a new razor component for testing i called it LocalStorage.razor<\/p>\n\n\n\n
@page \"\/localstorage\"\n\n@using BlazorLocalStorage.Service\n@inject LocalStorageService Storage\n\n<h1>Testing Local Storage!<\/h1>\n\n<input type=\"text\" @bind-value=\"Value\" @bind-value:event=\"oninput\" \/>\n\n<p>Current Value: @Value<\/p>\n\n<button @onclick=\"SetValue\">Save<\/button>\n<button @onclick=\"GetValue\">Read<\/button>\n\n@code{\n const string key = \"blazorKey\";\n\n public string Value { get; set; }\n\n async Task SetValue()\n {\n await Storage.SetLocalStorage(key, Value);\n }\n\n async Task GetValue()\n {\n Value = await Storage.GetFromLocalStorage(key);\n\n }\n}<\/code><\/pre>\n\n\n\nload the app and navigate to \/localstorage<\/a> <\/p>\n\n\n\ntype Hello World!<\/strong> and hit save<\/p>\n\n\n\n