はじめに
この記事はC#コードをrazorコンポーネント内に書かなくてもよくする方法を書いています。 個人的には小規模~中規模案件はコードビハインドを使用する選択をすると思います。いずれViewModelの記事とコードビハインドとの比較記事は書こうと思います。
FetchData.razor
をコードビハインドで書く
- ・
FetchDataModel.cs
ファイルを新規作成 - ・
FetchDataModel
クラスにComponentBase
を継承する。 - ・
FetchData.razor
内の、@code{ ~ }
で書かれているコードをFetchDataModel
クラスにコピペ。 - ・
HttpClient型のHttp
変数を作成し[Inject]
をつける。[Inject]
をつけると依存注入でNewされたインスタンスが自動でセットされる。 -
WeatherForecast
変数をprotectedに変更
ここまでのコードは以下の通り。
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using Qiita.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
namespace Qiita.Client.Pages
{
public class FetchDataModel : ComponentBase
{
[Inject]
protected HttpClient Http { get; set; }
protected WeatherForecast[] forecasts;
protected override async Task OnInitializedAsync()
{
try
{
forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");
}
catch (AccessTokenNotAvailableException exception)
{
exception.Redirect();
}
}
}
}
現時点ではFetchData.razor
コンポーネントからFetchDataModel
までの関連付けはされていない状態。
-
FetchData.razor
に@inherits FetchDataModel
を入れる。
@page "/fetchdata"
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Qiita.Shared
@attribute [Authorize]
@inherits FetchDataModel
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from the server.</p>
@if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}
動作確認
[Blazor関連のリンク]
Blazor WebAssembly プロジェクト作成(認証あり)
Blazor WebAssembly 初期プロジェクト構成の入門
Blazor WebAssembly Postgresを使うまで
Blazor WebAssembly コードビハインド
Blazor WebAssembly InputSelectの使い方