Sometimes it is necessary to store a "session variable" to store and track settings which live for the time of a session. In Blazor the whole concept of a session is different from how it was in asp.net before. One possibility for this task is to use cookies. This explains how this can be achieved. It is basically a copy from parts of this post in stackoverflow, adapted to radzen: https://stackoverflow.com/questions/54024644/how-do-i-create-a-cookie-client-side-using-blazor
First you need to define a service class in your radzen app:
using Microsoft.JSInterop;
namespace MyProject.Utils
{
public interface ICookie
{
public Task SetValue(string key, string value, int? days = null);
public Task<string> GetValue(string key, string def = "");
}
public class CookieS: ICookie
{
readonly IJSRuntime JSRuntime;
string expires = "";
public Cookie(IJSRuntime jsRuntime)
{
JSRuntime = jsRuntime;
ExpireDays = 300;
}
public async Task SetValue(string key, string value, int? days = null)
{
var curExp = (days != null) ? (days > 0 ? DateToUTC(days.Value) : "") : expires;
await SetCookie($"{key}={value}; expires={curExp}; path=/");
}
public async Task<string> GetValue(string key, string def = "")
{
var cValue = await GetCookie();
if (string.IsNullOrEmpty(cValue)) return def;
var vals = cValue.Split(';');
foreach (var val in vals)
if(!string.IsNullOrEmpty(val) && val.IndexOf('=') > 0)
if(val.Substring(0, val.IndexOf('=')).Trim().Equals(key, StringComparison.OrdinalIgnoreCase))
return val.Substring(val.IndexOf('=') + 1);
return def;
}
private async Task SetCookie(string value)
{
await JSRuntime.InvokeVoidAsync("eval", $"document.cookie = \"{value}\"");
}
private async Task<string> GetCookie()
{
return await JSRuntime.InvokeAsync<string>("eval", $"document.cookie");
}
public int ExpireDays
{
set => expires = DateToUTC(value);
}
private static string DateToUTC(int days) => DateTime.Now.AddDays(days).ToUniversalTime().ToString("R");
}
}
Then you add this service in startup.custom.cs similar to this:
partial void OnConfigureServices(IServiceCollection services)
{
services.AddScoped<UploadDbService>();
services.AddScoped<ICookie, CookieService>();
}
To have this available on every page you inject it in your MainLayout.razor.cs or whatever page you use as a Shared page.
public partial class MainLayoutComponent
{
[Inject]
protected ICookie cookie { get; set; }
}
No you can use code like this to read or write your cookie on every page derived from MainLayout.razor.cs:
await cookie.SetValue("mytest20", "Hello Mohsen!");
_message = await cookie.GetValue("mytest20");
In my case I want to select the tenant in a dropdown box in MainLayout like this:
I have declared a global variable in radzen to data bind my dropdown box to:
In the change event of this dropdown I write the cookie:
When page is loaded, my cookie is read like this: