Using browser local storage with Blazor
Project based on .NET Blazor Web App in Server render mode.
Blazor currently has no built-in function for utilizing local browser storage. However this feature can come in useful for storing user information or partially completed forms etc. Luckily implementing a class for facilitating this function is straightforward enough. Here I’ll run over the steps required to get local storage up and running in your Blazor web app.
Note: This method uses JSRuntime so make sure if you want to call it on page/component load you will need to run it on “OnAfterRender” rather than “OnInitialize” otherwise you will get an error.
Here is a screenshot of my file structure so you can see the additional files I’ve made and where I’ve placed them:
Making the javascript functions:
Within the wwwroot of your app, make a new javascript file (I’ve called mine LocalStorage.js) and enter the following code:
window.LocalStorageActions = {
setItem: function (key, value) {
localStorage.setItem(key, value);
},
getItem: function (key) {
return localStorage.getItem(key);
},
removeItem: function (key) {
localStorage.removeItem(key);
},
clearData: function () {
localStorage.clear();
}
}
These are the four functions we will need for setting, getting, removing and clearing local storage in the browser.
Make a C# class to call the functions:
To keep things tidy, I’ve put the C# class for calling the local storage functions and it’s interface into a folder called helpers, but you can put this wherever it’s most appropriate in your solution.
You can create a new .cs file and add the following code:
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
namespace BlazorLocalStorage.Helpers
{
public class LocalStorageHelper : ILocalStorageHelper
{
private readonly IJSRuntime _javaScript;
public LocalStorageHelper(IJSRuntime javaScript)
{
_javaScript = javaScript;
}
public async Task SetItem(string key, string value)
{
await _javaScript.InvokeAsync<string>(“LocalStorageActions.setItem”, key, value);
}
public async Task<string> GetItem(string key)
{
return await _javaScript.InvokeAsync<string>(“LocalStorageActions.getItem”, key);
}
public async Task RemoveItem(string key)
{
await _javaScript.InvokeAsync<string>(“LocalStorageActions.removeItem”, key);
}
public async Task ClearData()
{
await _javaScript.InvokeAsync<string>(“LocalStorageActions.clearData”);
}
}
}
To quickly produce the interface for this class you can right click the class name (LocalStorageHelper in this case) and select “Quick Actions and Refactoring” and then select “Extract Interface”
This will open a popup for extracting an interface from the class that you can select OK and a new file called ILocalStorageHelper.cs will appear and the LocalStorageHelper class will now inherit from the interface that’s been created.
Registering the new files ready for use:
Firstly we want to reference the new javascript file for use in the application. To do this go to the App.razor file and add the following line in the <body> section of the file.
<script src=”LocalStorage.js”></script>
Next, we need to register the LocalStorageHelper so it can be injected wherever we want to use it. To do this open the Program.cs file and add the following line before the builder.Build() method it called.
builder.Services.AddScoped<ILocalStorageHelper, LocalStorageHelper>();
Let’s try it out:
I’ve made a little example of the new class being used by modifying the Home.razor file to use the various functions we’ve created. Before adding the main code I have created a little css class to centre the content of the page to keep things neat. So you can add the following code snippet to app.css.
.center-screen {
display: flex;
justify-content: center;
align-items: center;
text-align: center;
min-height: 70vh;
}
Now we can go into the Home.razor file and replace the content with the following.
@PAGE “/”
@using BlazorLocalStorage.Helpers
@rendermode InteractiveServer
<PageTitle>Home</PageTitle>
<div class=”center-screen”>
<div>
<div class=”row”>
<label>Text-1</label>
<InputText class=”m-2″ @bind-Value=”Text1″ />
</div>
<div class=”row”>
<button class=”btn btn-success m-2″ @onclick=”Save”>Save</button>
<button class=”btn btn-info m-2″ @onclick=”Load”>Load</button>
<button class=”btn btn-warning m-2″ @onclick=”Remove”>Remove</button>
<button class=”btn btn-danger m-2″ @onclick=”Clear”>Clear</button>
</div>
</div>
</div>
@code {
[Inject] ILocalStorageHelper LocalStorage { get; set; }
public string Text1 { get; set; }
public async Task Save()
{
await LocalStorage.SetItem(“textData”, Text1);
}
public async Task Load()
{
Text1 = await LocalStorage.GetItem(“textData”);
}
public async Task Remove()
{
await LocalStorage.RemoveItem(“textData”);
}
public async Task Clear()
{
await LocalStorage.ClearData();
}
}
Apologies for the garish use of coloured buttons but it’s just meant to be an obvious demo. If you open the browsers developer tools and navigate to “Application” the select “Local Storage” you will be able to see the data stored, updated or removed as you use the demo.
If you refresh the page or close and open the browser and select load it will pull the stored data back in to the textbox.
That’s all there is to it!
If you want to see the project, I’ve stuck a copy up on github that you can have a look at:
https://github.com/DrGav/BlazorLocalStorage
Have yourselves a wonderful day,
Gavin.
Project based on .NET Blazor Web App in Server render mode. Blazor currently has no built-in function for utilizing local browser storage. However this feature can come in useful for storing user information or partially completed forms etc. Luckily implementing a class for facilitating this function is straightforward enough. Here I’ll run over the steps required to get local storage up and running in your Blazor web app. Note: This method uses JSRuntime so make sure if you want to call it on page/component load you will need to run it on “OnAfterRender” rather than “OnInitialize” otherwise you will get an error. Here is a screenshot of my file structure so you can see the additional files I’ve made and where I’ve placed them: Making the javascript functions:Within the wwwroot of your app, make a new javascript file (I’ve called mine LocalStorage.js) and enter the following code: window.LocalStorageActions = {
setItem: function (key, value) {
localStorage.setItem(key, value);
},
getItem: function (key) {
return localStorage.getItem(key);
},
removeItem: function (key) {
localStorage.removeItem(key);
},
clearData: function () {
localStorage.clear();
}
} These are the four functions we will need for setting, getting, removing and clearing local storage in the browser. Make a C# class to call the functions:To keep things tidy, I’ve put the C# class for calling the local storage functions and it’s interface into a folder called helpers, but you can put this wherever it’s most appropriate in your solution.You can create a new .cs file and add the following code: using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
namespace BlazorLocalStorage.Helpers
{
public class LocalStorageHelper : ILocalStorageHelper
{
private readonly IJSRuntime _javaScript;
public LocalStorageHelper(IJSRuntime javaScript)
{
_javaScript = javaScript;
}
public async Task SetItem(string key, string value)
{
await _javaScript.InvokeAsync<string>(“LocalStorageActions.setItem”, key, value);
}
public async Task<string> GetItem(string key)
{
return await _javaScript.InvokeAsync<string>(“LocalStorageActions.getItem”, key);
}
public async Task RemoveItem(string key)
{
await _javaScript.InvokeAsync<string>(“LocalStorageActions.removeItem”, key);
}
public async Task ClearData()
{
await _javaScript.InvokeAsync<string>(“LocalStorageActions.clearData”);
}
}
} To quickly produce the interface for this class you can right click the class name (LocalStorageHelper in this case) and select “Quick Actions and Refactoring” and then select “Extract Interface” This will open a popup for extracting an interface from the class that you can select OK and a new file called ILocalStorageHelper.cs will appear and the LocalStorageHelper class will now inherit from the interface that’s been created. Registering the new files ready for use:Firstly we want to reference the new javascript file for use in the application. To do this go to the App.razor file and add the following line in the <body> section of the file. <script src=”LocalStorage.js”></script> Next, we need to register the LocalStorageHelper so it can be injected wherever we want to use it. To do this open the Program.cs file and add the following line before the builder.Build() method it called. builder.Services.AddScoped<ILocalStorageHelper, LocalStorageHelper>(); Let’s try it out:I’ve made a little example of the new class being used by modifying the Home.razor file to use the various functions we’ve created. Before adding the main code I have created a little css class to centre the content of the page to keep things neat. So you can add the following code snippet to app.css. .center-screen {
display: flex;
justify-content: center;
align-items: center;
text-align: center;
min-height: 70vh;
} Now we can go into the Home.razor file and replace the content with the following. @PAGE “/”
@using BlazorLocalStorage.Helpers
@rendermode InteractiveServer
<PageTitle>Home</PageTitle>
<div class=”center-screen”>
<div>
<div class=”row”>
<label>Text-1</label>
<InputText class=”m-2″ @bind-Value=”Text1″ />
</div>
<div class=”row”>
<button class=”btn btn-success m-2″ @onclick=”Save”>Save</button>
<button class=”btn btn-info m-2″ @onclick=”Load”>Load</button>
<button class=”btn btn-warning m-2″ @onclick=”Remove”>Remove</button>
<button class=”btn btn-danger m-2″ @onclick=”Clear”>Clear</button>
</div>
</div>
</div>
@code {
[Inject] ILocalStorageHelper LocalStorage { get; set; }
public string Text1 { get; set; }
public async Task Save()
{
await LocalStorage.SetItem(“textData”, Text1);
}
public async Task Load()
{
Text1 = await LocalStorage.GetItem(“textData”);
}
public async Task Remove()
{
await LocalStorage.RemoveItem(“textData”);
}
public async Task Clear()
{
await LocalStorage.ClearData();
}
} Apologies for the garish use of coloured buttons but it’s just meant to be an obvious demo. If you open the browsers developer tools and navigate to “Application” the select “Local Storage” you will be able to see the data stored, updated or removed as you use the demo. If you refresh the page or close and open the browser and select load it will pull the stored data back in to the textbox. That’s all there is to it! If you want to see the project, I’ve stuck a copy up on github that you can have a look at:https://github.com/DrGav/BlazorLocalStorage Have yourselves a wonderful day,Gavin. Read More