Razorコンポーネントからクラスメソッドを呼び出す - Blazorアプリケーションからのクラスオブジェクトのアクセス

Razorコンポーネントからクラスメソッドを呼び出すコードを紹介します。

概要

Razorコンポーネントのrazorファイル中の @codeディレクティブ内でC#のコードを記述でき処理を実行できますが、処理の規模が大きくなる場合、razorファイル中ではなく、別のコードファイルやクラスで処理を記述したい場合があります。この記事ではRazorコンポーネントからクラスオブジェクトにアクセスしてクラスのメソッドを呼び出すコードを紹介します。

プログラム例

事前準備

Blazorアプリケーションを作成し、メイン画面のRazorコンポーネントを作成します。作成手順の詳細はこちらの記事を参照してください。ルーティングコンポーネント、フォールバックページ、画面のRazorコンポーネントを作成します。

クラスのコードの追加

ロジックを実装するクラスを実装します。今回はアプリケーションルートディレクトリに"Module"フォルダを作成し、作成したフォルダ内に"MyProc.cs"ファイルを追加します。


MyProc.csファイルは下記のコードを記述します。
MyProc.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SimpleClassCall.Module
{
  public class MyProc
  {
    public int AddOperation(int a, int b)
    {
      return a + b;
    }
  }
}

解説

クラスに下記のメソッドを実装します。2つのint型の引数を受け取り、その和を戻り値として返すメソッドです。
  public int AddOperation(int a, int b)
  {
    return a + b;
  }

画面のRazorコンポーネントの実装

画面のRazorコンポーネントを実装します。下記のコードを記述します。
Index.razor
<h3>Index</h3>
@page "/"
<h3>Class Call Demo</h3>

<input id="text1" type="text" @bind="@value1" />
<input id="text2" type="text" @bind="@value2" />
<br />
<button @onclick="ButtonClick">Button1</button>
<div>@ResultText</div>

@code {
  string value1;
  string value2;
  string ResultText;

  void ButtonClick()
  {
      int value_i1 = Convert.ToInt32(value1);
      int value_i2 = Convert.ToInt32(value2);
      Module.MyProc myproc = new Module.MyProc();
      int result_i = myproc.AddOperation(value_i1, value_i2);
      ResultText = string.Format("結果は {0:d} です。",result_i);
  }
}

解説

下記のコードでテキストボックスを配置します。@bindの記述により、text1のテキストボックスに入力された値は value1 変数に、text2のテキストボックスに入力された値は value2 変数に格納されます。
<input id="text1" type="text" @bind="@value1" />
<input id="text2" type="text" @bind="@value2" />

下記のコードでボタンを配置します。ボタンクリック時には @onclickに記述したButtonClick関数を呼び出します。
<button @onclick="ButtonClick">Button1</button>

処理の結果を表示する部分です。ResultText変数の値を表示します。~
<div>@ResultText</div>

ボタンがクリックされると下記のコードが実行されます。2つのテキストボックスに入力された値を数値に変換して value_i1, value_i2 変数に代入します。
続いて先に追加した MyProcクラスのインスタンスを作成します。今回MyProc.csファイルはModuleフォルダ内に配置したため、MyProcクラスの名前空間は "Module.MyProc" となります。
作成したインスタンスオブジェクト myproc オブジェクトの AddOperation メソッドを呼び出します。引数には value_i1, value_i2 変数を与えます。結果はAddOperation メソッドの戻り値が返ります。戻り値を画面に表示します。
  void ButtonClick()
  {
      int value_i1 = Convert.ToInt32(value1);
      int value_i2 = Convert.ToInt32(value2);
      Module.MyProc myproc = new Module.MyProc();
      int result_i = myproc.AddOperation(value_i1, value_i2);
      ResultText = string.Format("結果は {0:d} です。",result_i);
  }

実行結果

プロジェクトを実行します。下図のページが表示されます。


テキストボックスに数値を入力します。今回は12と6の値を入力しました。入力後[Button1]ボタンをクリックします。


ボタンの下部に結果のメッセージが表示されます。入力した数値の12と6の和である18が表示されていることが確認できます。razorコンポーネントの画面からC#のクラスのメソッドの呼び出しができていることが確認できます。

参考:他のファイルのコード

App.razor
<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" />
    </Found>
    <NotFound>
        <LayoutView>
            <p>Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>
_Imports.razor
@using System.Net.Http
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace SimpleClassCall
{
  public class Startup
  {
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddRazorPages();
      services.AddServerSideBlazor();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
      }

      app.UseStaticFiles();
      app.UseRouting();

      app.UseEndpoints(endpoints =>
      {
        endpoints.MapBlazorHub();
        endpoints.MapFallbackToPage("/_Host");
      });
    }
  }
}
/Pages/_Host.cshtml
@page
@namespace SimpleClassCall.Pages

<!DOCTYPE html>
<html lang="ja">
<head>
    <base href="~/" />
</head>
<body>
    <app>
        @(await Html.RenderComponentAsync<App>(RenderMode.ServerPrerendered))
    </app>
    <script src="_framework/blazor.server.js"></script>
</body>
</html>
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2019-10-08
作成日: 2019-10-08
iPentec all rights reserverd.