Memory storage

✅ Similar to Blazor Server

Memory storage is an ideal choice for temporary storage that does not need to be persisted beyond the current session.

  • What is Memory storage?
  • Set up the base code for interacting with Memory storage.
  • Use Memory storage.
You can download the example code used in this topic on GitHub.

What is Memory storage?

In Blazor, memory storage involves storing data in variables within a web application's memory instead of external storage like databases or local storage. One major advantage of memory storage is that developers can directly access it using C# code, rather than relying on JavaScript APIs. Additionally, memory storage is strongly-typed, allowing for more efficient and accurate data handling. Data in memory storage is also isolated by browser tab, providing a level of security and organization.


Set up the base code for interacting with Memory storage

  1. Define a C# class with the properties that will hold your data. For instance, here is an example class named MemoryStorageUtility that uses a dictionary to store data:
public class MemoryStorageUtility
{
    public Dictionary<string, object> Storage { get; set; } = new();
}
You may choose a different data type if necessary.
  1. Register the MemoryStorageUtility class in the Program.cs file:
builder.Services.AddScoped<MemoryStorageUtility>();

Use Memory storage

Once you have completed all the previous steps, you can use the Memory storage as follows:

@inject MemoryStorageUtility MemoryStorageUtility

<h3>BrowserStorageDemonstrate</h3>
<form>
    <label>
        Key
        <input type="text" @bind-value="Key" />
    </label>
    <label>
        Value
        <input type="text" @bind-value="Value" />
    </label>
    <button type="button" @onclick="SetValue">Set Value</button>
</form>
<div>Stored Value: @StoredValue</div>
<button type="button" @onclick="GetValue">Get Value</button>
<button type="button" @onclick="Remove">Remove Value</button>
<button type="button" @onclick="ClearAll">Clear All</button>

@code {
    public string Key { get; set; } = "";
    public string Value { get; set; } = "";
    public string StoredValue { get; set; } = "";

    public void SetValue()
    {
        MemoryStorageUtility.Storage[Key] = Value;
    }

    public void GetValue()
    {
        if (MemoryStorageUtility.Storage.TryGetValue(Key, out var value))
        {
            StoredValue = value.ToString()!;
        }
        else
        {
            StoredValue = "";
        }
    }

    public void Remove()
    {
        MemoryStorageUtility.Storage.Remove(Key);
    }

    public void ClearAll()
    {
        MemoryStorageUtility.Storage.Clear();
    }
}
BLAZOR SCHOOL
Designed and built with care by our dedicated team, with contributions from a supportive community. We strive to provide the best learning experience for our users.
Docs licensed CC-BY-SA-4.0
Copyright © 2021-2024 Blazor School
An unhandled error has occurred. Reload 🗙