はじめに
この記事は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 プロジェクト作成(認証あり)](https://qiita.com/pero_88/items/be142d5d0ba92e5c91d0) [Blazor WebAssembly 初期プロジェクト構成の入門](https://qiita.com/pero_88/items/ced1028ad536a43fec1d) [Blazor WebAssembly Postgresを使うまで](https://qiita.com/pero_88/items/23e88a1d2bc3659b9946) [Blazor WebAssembly コードビハインド](https://qiita.com/pero_88/items/be871f4ac63868f048f0) [Blazor WebAssembly InputSelectの使い方](https://qiita.com/pero_88/items/3eddcd1aedf8bbc8441b)
