✅ Similar to Blazor WebAssembly
Memory storage is an ideal choice for temporary storage that does not need to be persisted beyond the current session.
You can download the example code used in this topic on GitHub.
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.
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.
MemoryStorageUtility
class in the Program.cs file:builder.Services.AddScoped<MemoryStorageUtility>();
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(); } }