Blazorフォームの基本とは?|ASP.NET×Blazor入門 4.2

4.2 ユーザー入力とフォーム

Webアプリに欠かせない「フォーム入力」。名前・メールアドレス・パスワード・選択肢──これらを安全かつ簡潔に扱う仕組みが、Blazorには用意されています。 C#だけで完結し、JavaScriptに頼らずにバリデーションまでできる。その世界を体験してみましょう。

基本のフォーム構造

Blazorでは、<EditForm> コンポーネントがフォームの中心になります。 入力内容は C# のモデルと連動しており、型安全なフォームが簡単に作れます。

<EditForm Model="@user" OnValidSubmit="HandleValidSubmit">
  <DataAnnotationsValidator />
  <ValidationSummary />

  <div>
    <label for="name">名前:</label>
    <InputText id="name" class="form-control" @bind-Value="user.Name" />
  </div>

  <div>
    <label for="email">メールアドレス:</label>
    <InputText id="email" class="form-control" type="email" @bind-Value="user.Email" />
  </div>

  <button type="submit">送信</button>
</EditForm>

@code {
    private UserModel user = new();

    private void HandleValidSubmit()
    {
        Console.WriteLine($"送信された名前: {user.Name}");
    }

    public class UserModel
    {
        [Required(ErrorMessage = "名前は必須です")]
        public string Name { get; set; } = "";

        [Required]
        [EmailAddress(ErrorMessage = "メールアドレスの形式が正しくありません")]
        public string Email { get; set; } = "";
    }
}

よく使うInputコンポーネント

  • InputText:テキスト、メール、パスワードなど
  • InputNumber:数値(int, doubleなど)
  • InputSelect:セレクトボックス
  • InputCheckbox:チェックボックス
  • InputDate:日付入力

どれも @bind-Value を使って双方向バインディングできます。 通常のHTML要素に @bind を使うのと同様、これらのInput系コンポーネントはバリデーションとの統合がしやすくなっています。

バリデーションの基本

モデルに DataAnnotations 属性を付ければ、バリデーションが有効になります。

public class UserModel
{
    [Required(ErrorMessage = "名前は必須です")]
    public string Name { get; set; } = "";

    [Required]
    [EmailAddress(ErrorMessage = "メールアドレスの形式が正しくありません")]
    public string Email { get; set; } = "";
}

<DataAnnotationsValidator /><ValidationSummary /> をフォームに追加することで、 入力チェックとエラーメッセージの表示が簡単にできます。

まとめ

  • <EditForm> とモデルでフォームを構築
  • 各種 Input コンポーネントで型に応じた入力
  • DataAnnotations によるバリデーション

次のセクション「4.3 イベントの種類とカスタムイベント」では、よりインタラクティブな体験をつくるためのイベント処理について学んでいきます。

2025-04-18

下田 昌平

開発に関するインプットをアウトプットしています。