Razor Pages でテキストボックスの値を取得する - BindPropetyによるフォームの値の取得 - ASP.NET Core

Razor Pages でBindPropetyを利用して、テキストボックスなどの値をPOST時に取得するコードを紹介します。

概要

ASP.NET CoreのRazorページでテキストボックスなどの値を取得するには、BindPropertyの機能を利用します。取得する値のモデルとなるクラスを実装し、ページモデルのメンバ変数としてBindPropety属性を付けて宣言します。

プログラム例

コード

下記のコードを記述します。
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 SimpleButtonBindProperty
{
  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();
    }

    // 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.UseRouting();

      app.UseEndpoints(endpoints =>
      {
        if (env.IsDevelopment()) {
          app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
          endpoints.MapRazorPages();
        });
      });
    }
  }
}

モデルクラス

SimpleModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SimpleButtonBindProperty
{
  public class SimpleModel
  {
    public string Name { get; set; }
    public string Code { get; set; }
  }
}

ページ

Button.cshtml
@page "/Button"
@model SimpleButtonBindProperty.ButtonModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
  Layout = null;
}

<!DOCTYPE html>

<html>
<head>
  <meta name="viewport" content="width=device-width" />
  <title>Button</title>
</head>
<body>
  <div>Button Demo</div>
  <form method="post">
    Code:<input type="text" asp-for="data.Code"/><br/>
    Name:<input type="text" asp-for="data.Name" /><br />
    <input type="submit" value="Button1" />
  </form>
</body>
</html>
Button.cshtml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace SimpleButtonBindProperty
{
  public class ButtonModel : PageModel
  {
    [BindProperty]
    public SimpleModel data { get; set; }

    public void OnGet()
    {

    }
    public IActionResult OnPost()
    {
      return RedirectToPage("/ButtonResult",new { name= data.Name, code=data.Code });
    }
  }
}
ButtonResult.cshtml
@page  "/ButtonComplete/{name?}/{code?}"
@model SimpleButtonBindProperty.Pages.ButtonResultModel
@{
}
<!DOCTYPE html>

<html>
<head>
  <meta name="viewport" content="width=device-width" />
  <title>Button</title>
</head>
<body>
  <div>Button Demo</div>
  <div>Name : @Model.NameText</div>
  <div>Code : @Model.CodeText</div>
</body>
</html>
ButtonResult.cshtml
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace SimpleButtonBindProperty.Pages
{
  public class ButtonResultModel : PageModel
  {
    public string NameText;
    public string CodeText;

    public void OnGet(string name = "", string code = "")
    {
      NameText = name;
      CodeText = code;
    }
  }
}

解説

Startup.cs ファイルは一般的なRazor Pagesアプリケーションのコードと同じです。詳しくはこちらの記事を参照してください。

モデル

モデルクラスのSimpleModel.cs ファイルにはフォームで取得する値の項目を宣言します。今回の例では、NameとCodeのフィールドを用意しますので、モデルクラスにもName,Code のプロパティを実装します。なお、フィールドはプロパティで実装する必要があります。(メンバ変数の実装では正しく動作しません。)

ページ

Button.cshtml.cs ファイルにはモデルクラスのSimpleModel型のプロパティを実装します。今回の例ではdataプロパティとします。
  [BindProperty]
  public SimpleModel data { get; set; }

Submitボタンがクリックされた際の処理を OnPostメソッドに実装します。今回のコードでは、RedirectToPage メソッドを呼び出し、ButtonResult.cshtml ファイルのページにリダイレクトします。テキストボックスに入力された内容はdata.Nameプロパティと、data.Codeプロパティに設定されていますので、この値をパラメーターにして渡します。
  public IActionResult OnPost()
  {
    return RedirectToPage("/ButtonResult",new { name= data.Name, code=data.Code });
  }

Button.cshtml ファイルにはテキストボックス2つとサブミットボタンを配置します。
テキストボックスのinputタグには asp-for属性を追加します。asp-for属性の値にページモデルのクラスのBindProperty属性を設定したプロパティのフィールド名を設定します。
  <form method="post">
    Code:<input type="text" asp-for="data.Code"/><br/>
    Name:<input type="text" asp-for="data.Name" /><br />
    <input type="submit" value="Button1" />
  </form>

ButtonResult.cshtml.cs ファイルにはOnGetメソッドを実装します。ここで渡されたパラメーターの取得の処理を実装します。パラメーターは引数として渡されますので、渡された値をメンバ変数に代入しています。
    public void OnGet(string name = "", string code = "")
    {
      NameText = name;
      CodeText = code;
    }

ButtonResult.cshtml では、@pageディレクティブでパラメーターつきのURLを受け入れるようにします。下記のコードで2つのパラメーターを受け取れるようになります。
@page  "/ButtonComplete/{name?}/{code?}"

@ページモデル.メンバ変数 の記述でメンバ変数の値をページに表示します。OnGetメソッドで取得したパラメーターの値を画面に表示します。
  <div>Name : @Model.NameText</div>
  <div>Code : @Model.CodeText</div>

実行結果

プロジェクトを実行します。Webブラウザで (アプリケーションルートURL)/Button のURLを開きます。下図のページが表示されます。


テキストボックスに値を入力します。入力後[Button1]ボタンをクリックします。


(アプリケーションルートURL)/ButtonComplete のURLに遷移します。テキストボックスの入力内容がURLパラメーターに設定され、ページにテキストボックスに入力した内容が表示されます。


BindPropertyを利用して、テキストボックスの入力内容を取得できました。

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2020-01-08
作成日: 2020-01-08
iPentec all rights reserverd.