LoginSignup
0
0

More than 1 year has passed since last update.

Blazor WebAssembly コードビハインド

Last updated at Posted at 2021-09-12

はじめに

この記事は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>
}

動作確認

エラーなくforecastページにアクセス出来ればOK
キャプチャ11.PNG



[Blazor関連のリンク]
Blazor WebAssembly プロジェクト作成(認証あり)
Blazor WebAssembly 初期プロジェクト構成の入門
Blazor WebAssembly Postgresを使うまで
Blazor WebAssembly コードビハインド
Blazor WebAssembly InputSelectの使い方

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