9
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Blazor WebAssembly で input タグの値をリアルタイムに双方向バインディングしたい

Last updated at Posted at 2020-08-06

Blazor WebAssembly

Blazor WebAssemblyはWebAssemblyによって.NET環境がブラウザに用意されC#で書いたコードがそのまま動いちゃうすごいやつです。そしてきちんとSPAフレームワークになっているのですがDOMとモデルの双方向バインディングで少しハマったので記録として残しておきます。

ASP.NET Core Blazor の概要
image.png

Blazor WebAssemblyは、.NETとC#などを用いてWebブラウザ上で実行可能なWebアプリケーションを開発できるフレームワークおよび実行系です。
Blazor WebAssembly 3.2.0はBlazor WebAssemblyとしてフル機能が実装され、本番運用に対応したバージョンです。これによりBlazor WebAssemblyは正式版としてリリースされたことになります。

publickeyより引用

要件

下記のようなinputタグの値を変えたら、リアルタイムでh2タグのインナーテキストも変更させることが要件です。

<h2>@name</h2>
<input type="text" />

NG実装

双方向バンディングの@bindを使ってみます。

NG.razor
<h2>@name</h2>
<input type="text" @bind="name" />

@code {
    string name = "";
}

上記では双方向にバインドできていますが、フォーカスが離れたり、エンターを押したりしないと反映されません

OK実装①

@bind-valueで双方向バインディングしつつ、@bind-value:eventでインプットイベント拾います。

OK1.razor
<h2>@name</h2>
<input type="text" @bind-value="name" @bind-value:event="oninput" />

@code {
    string name = "";
}

フォーカスアウトやエンター入力で発生する@bind異なり、テキストボックスの値が変更されたときにイベントが発生します。
単純な実装でコード量が少ないです。

OK実装②

@oninputで入力時に実行されるメソッドをバンディングします。
バインドしたメソッド内でnameの値を書き換えて画面に反映します。
値の変更だけでなく、何かしら処理をしたい場合に使います。

OK2.razor
<h2>@name</h2>
<input type="text" value="@name" @oninput="HandleInput" />

@code {
    string name = "";

    void HandleInput(ChangeEventArgs  e)
    {
        // メソッド内でなにか処理をできる
        name = e.Value.ToString();
    }
}

おまけ

@bindは下記のように@onchangeを使ったコードに内部的に変換されるらしく、
1つの要素に対して@bind@onchangeを同時に使用することはできないようです。

実際のコード
<input @bind="CurrentValue" />
内部的なコード
<input type="text" value="@CurrentValue"
    @onchange="@((ChangeEventArgs __e) => CurrentValue = __e.Value.ToString())" />
9
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?