BlazerでURLクエリを受け取る
2019年3月14日 (木) 05:06時点における180.15.192.154 (トーク)による版 (ページの作成:「BlazerでURLクエリを受け取りたい。 == 準備 == NuGetから「Microsoft.AspNetCore.WebUtilities」をインストールする インストールする際…」)
BlazerでURLクエリを受け取りたい。
準備編集
NuGetから「Microsoft.AspNetCore.WebUtilities」をインストールする インストールする際には最新のものではなくプロジェクト内で既に使われているASP .NET Coreのバージョンにあわせること。
実装編集
- Hello.cshtml
@page "/hello"
@implements IDisposable
@inject Microsoft.AspNetCore.Blazor.Services.IUriHelper UriHelper
<h1>Hello @Type World!</h1>
<MainMenu />
@functions {
private string Type { get; set; }
protected override void OnInit()
{
RefreshType();
UriHelper.OnLocationChanged += OnLocationChanges;
}
private void OnLocationChanges(object sender, string location) => RefreshType();
private void RefreshType()
{
var uri = new Uri(UriHelper.GetAbsoluteUri());
Type = Microsoft.AspNetCore.WebUtilities
.QueryHelpers.ParseQuery(uri.Query).TryGetValue("type", out var type) ? type.First() : "";
this.StateHasChanged();
}
public void Dispose()
{
UriHelper.OnLocationChanged -= OnLocationChanges;
}
}