LoginSignup
3
3

More than 1 year has passed since last update.

Blazorでselectタグを初期値に戻す方法

Last updated at Posted at 2022-08-04

0.Intro

ちょっとした開発でBlazorを使っています。不慣れなので如何にもBlazorという要素は使用しておらずinputタグ,Buttonタグ等でやりくりしています。それでも所謂SPAの便利さを十分に享受できて便利になったとつくづく思います。
そんな中、あるデータのグルーピングをselectタグから選んだキーワードで変えながら比較して見るという案件がありました。キーワードを選ばせてグルーピングを変えるという機能は簡単にできたのですが、ではselectタグを初期値に戻すにはどうすれば良いか、大変悩みました。
画面表示時の最初の表示時はselectタグのvalueに紐付けた変数に値を代入するとその値に設定してくれます。ただ初回以降selectの値を変更するとvalueに紐付けた変数に値を代入しても変更されません。ある値に設定したいという時の第一選択肢はbindなのですが効きませんでした。selectにて値変更した後の後続の処理を入れたいので@onchangeを使っていました。なので@bindだとエラーにもなります。
そんな中、色々調べた結果以下のようにすると実現できました。

1.Code

@page "/selsample"

<PageTitle>SelSample</PageTitle>


 <select @bind=SelValue>
    @foreach(var t in @_menu)
    {
        <option value=@t>@t</option>
    }

</select>

    @if(_countlist.Count !=0)
    {
        @foreach(var i in @_countlist)
        {
            <p>@i</p>
        }
    }
    <button @onclick="Reset">
        Reset
    </button>

@code {

    List<string> _menu = new List<string> { "1", "3", "5", "7", "9"};
    List<string> countlist = new List<string> { "1", "2", "3", "4", "5","6", "7", "8", "9", "10"};
    List<string> _countlist = new List<string>();
    private string _SelValue = "1";
    
    private void Reset()
    {
        SelValue = "1";
    }

    private string SelValue
    {
        get {
            _countlist = countlist.Where(e => int.Parse(e) >= int.Parse(_SelValue)).ToList();
            return _SelValue; 
        
        }
        set
        {
                _SelValue = value;            
        }
    }
}

2.Explanation

カスタム バインディング形式、なるほど思いました。これだとバインドしつつ、必要な処理も書けますね。
目的通りの動きになりました。

簡単ではありますが大変悩みましたので共有させていただきます。

3
3
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
3
3