概要
Blazorのコンポーネントでロジックとビューを分離して記載する方法のメモ。
よくある記載例
Blazorのサンプルコードの多くは、下記のようにrazorファイルの中にHTML要素とバインドするC#コードを合わせて記載しています。
@page"/counter"<h1>Counter</h1><p>Currentcount:@currentCount</p><buttonclass="btnbtn-primary" @onclick="IncrementCount">Click me</button>
@code{privateintcurrentCount=0;privatevoidIncrementCount(){currentCount++;}}
このような手法とは別に、razorコンポーネントとC#コードを分離して記載するコードビハインドといった記載も可能です。今回はその方法を紹介します。
コードビハインドでの記載方法
モデル(C#コード)
まずは元となるC#側のコードを作成します。
publicclassCounterModel:ComponentBase{publicintCurrentCount{get;privateset;}publicvoidIncrementCount(){CurrentCount++;}}
分離しない場合の変更点としては下記になります。
- ComponentBaseクラスを継承したクラスとする。(Microsoft.AspNetCore.Components)
- ビューからバインドする変数及び関数をprivateからpublicにする。
ビュー(razorコンポーネント)
次にrazorコンポーネント側を作成します。
@page"/counter"@inheritsCounterModel<h1>Counter</h1><p>Currentcount:@CurrentCount</p><buttonclass="btnbtn-primary" @onclick="IncrementCount">Click me</button>
分離しない場合のrazorコンポーネントとの違いは下記になります。
- C#コードの代わりにデータバインドするモデルクラス名をinheritsで記載する。
DIの方法
Inject属性を付与したプロパティを使用することで依存性の注入が可能になります。
(具体的なクラスの指定は通常通りStarup.csから指定する。)
publicclassCounterModel:ComponentBase{[Inject]protectedIDataAccessDataRepository{get;set;}publicintCurrentCount{get;privateset;}publicvoidIncrementCount(){CurrentCount++;}}
まとめ
簡単にですが、Blazorにおけるコードビハインドの方法を紹介しました。
ロジックとビューを分離することで、下記のようなメリットなどが得られます。
- ロジックに対するUnitTestの記載が可能
- 基底のコンポーネントクラスの作成などによる共通処理の作成
参考資料
https://www.telerik.com/blogs/using-a-code-behind-approach-to-blazor-components
https://docs.microsoft.com/ja-jp/aspnet/core/blazor/dependency-injection?view=aspnetcore-3.0
https://gunnarpeipman.com/blazor-code-behind/