Skip to content
master
Switch branches/tags
Go to file
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
src
 
 
 
 
 
 
 
 

Blazor Local and Session Storage Support

Installation

PM> Install-Package Cloudcrate.AspNetCore.Blazor.Browser.Storage

See it in Action

Check out Steve Sanderson's demo at NDC Minnesota, at minute 48

Usage

Add Services to Dependency Injection

services.AddStorage();

Add Javascript file to your index.html or _Host.cshtml page in <body> after either <script src="_framework/blazor.webassembly.js"></script> or <script src="_framework/blazor.server.js"></script> depending on what architecture you are using.

<script src="_content/Cloudcrate.AspNetCore.Blazor.Browser.Storage/Storage.js"></script>

Client-Side

Inject and use Storage

@using Cloudcrate.AspNetCore.Blazor.Browser.Storage;
@inject LocalStorage Storage

<input type="text" @bind="value" />
<button @onclick="SetValue">Set</button>
<button @onclick="GetValue">Get</button>


@code
{
    string value;

    void SetValue()
    {
        Storage.SetItem("storageKey", value);
    }

    void GetValue()
    {
        value = Storage.GetItem("storageKey");
    }
}

Server-Side

Inject and use Storage

@using Cloudcrate.AspNetCore.Blazor.Browser.Storage;
@inject LocalStorage Storage

<input type="text" @bind="value" />
<button @onclick="SetValue">Set</button>
<button @onclick="GetValue">Get</button>


@code
{
    string value;

    async Task SetValue()
    {
        await Storage.SetItemAsync("storageKey", value);
    }

    async Task GetValue()
    {
        value = await Storage.GetItemAsync("storageKey");
    }
}

Events

Using storage native event: StorageEvent

protected override void OnInit()
{
    Storage.StorageChanged += HandleStorageChanged;
}

void HandleStorageChanged(object sender, StorageEventArgs e)  
{  
    Console.WriteLine($"Value for key {e.Key} changed from {e.OldValue} to {e.NewValue}");
} 

public void Dispose()
{
    Storage.StorageChanged -= HandleStorageChanged;
}

Contributors