Blazorアプリケーションでボタンやリンクのクリックの処理で別のページに遷移する

https://www.ipentec.com/destocument/csharp-blazor-application-navigate-page

本家が一番。
要は以下を実施する。
①@inject NavigationManager NavigationManagerを挿入
②protected NavigationManager NavManager { get; set; }をCode内に挿入
③Code内の以下を編集
protected override void OnInitialized()
public void Dispose()
private void NavigateToCounterComponent()

@page "/Test"
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@inject HttpClient Http;
@inject NavigationManager NavigationManager

<h3>ObjectDetectionFilelist</h3>
<a href="" @onclick="LinkClick">Navigate to the Counter component with link</a>
<button class="btn btn-primary" @onclick="NavigateToCounterComponent">
    Navigate to the Counter component with botton
</button>


@code {

    protected NavigationManager NavManager { get; set; }
    private int Value { get; set; }


    protected override void OnInitialized()
    {
        NavigationManager.LocationChanged += HandleLocationChanged;
    }

    private void HandleLocationChanged(object? sender, LocationChangedEventArgs e)
    {
        //Logger.LogInformation("URL of new location: {Location}", e.Location);
        Console.WriteLine($"{DateTime.Now}:URL of new location: {Value}", e.Location);
    }

    public void Dispose()
    {
        NavigationManager.LocationChanged -= HandleLocationChanged;
    }



    protected void LinkClick()
    {
        //なぜかうまくいかない。
        Console.WriteLine($"{DateTime.Now}: Test::ButtonClickが呼び出されました。: {Value}");
        NavManager.NavigateTo("counter", false);
        Console.WriteLine($"{DateTime.Now}: Test::ButtonClickが終了しました。: {Value}");
    }

    private void NavigateToCounterComponent()
    {
        //なぜかうまくいく。
        Console.WriteLine($"{DateTime.Now}: Test::NavigateToCounterComponentが呼び出されました。: {Value}");
        NavigationManager.NavigateTo("counter");
        Console.WriteLine($"{DateTime.Now}: Test::NavigateToCounterComponentが終了しました。: {Value}");
    }
}

ここから先は

0字

¥ 100

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