Blazor:Sessionの使い方

ASP.NET Core Blazor state management | Microsoft Docs
素晴らしいことを書いてくれているサイトを発見
https://zenn.dev/yoshi1220/articles/8f4783ade9c06d

Browser storage

For transient data that the user is actively creating, a commonly used storage location is the browser's localStorage and sessionStorage collections:

  • localStorage is scoped to the browser's window. If the user reloads the page or closes and re-opens the browser, the state persists. If the user opens multiple browser tabs, the state is shared across the tabs. Data persists in localStorage until explicitly cleared.

  • sessionStorage is scoped to the browser tab. If the user reloads the tab, the state persists. If the user closes the tab or the browser, the state is lost. If the user opens multiple browser tabs, each tab has its own independent version of the data

c# - How to store session data in server-side blazor - Stack Overflow

@page "/"
@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@inject ProtectedSessionStorage ProtectedSessionStore

User name: @UserName
<p/><input value="@UserName" @onchange="args => UserName = args.Value?.ToString()" />
<button class="btn btn-primary" @onclick="SaveUserName">Save</button>

@code {
    private string UserName;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (firstRender)
        {
            UserName = (await ProtectedSessionStore.GetAsync<string>("UserName")).Value ?? "";
            StateHasChanged();
        }
    }
    
    private async Task SaveUserName() {
        await ProtectedSessionStore.SetAsync("UserName", UserName);
    }
}

Sessionを保存するClassを作成しておく。
Project直下など適当な場所に配置。

namespace ProjectName.Client
{
    public class StateContainer
    {
       private int? id;
        private string? title;

        public int Session_Id
        {
            get => id?? 0;
            set
            {
                id= value;
                NotifyStateChanged();
            }
        }

        public string Session_Title
        {
            get => title?? string.Empty;
            set
            {
                title= value;
                NotifyStateChanged();
            }
        }
    }
}

Razorファイルでそれを使用する場合。

@inject StateContainer StateContainer;
<button @onclick="(e=>ChangePropertyValue(_id, _title))">Jump</button>
@code {
    int _id; //適当に何か入れてください。
    string _title; //適当に何か入れてください。

    //この事例ではボタンが押されたときにSessionに情報を入れる。
    private void ChangePropertyValue(int _id, string _title)
    {
        StateContainer.Session_Id = _id;
        StateContainer.Session_Title = _title;
    }


ここから先は

0字

¥ 100

この記事が気に入ったらサポートをしてみませんか?