記事詳細


投稿日
2026年09月05日07時56分
タイトル

ASP.NET Core MVC:  CreateViewのform内で、「入金」をtrue、「出金」をfalse、というフラッグとして利用するbool型の「InOut」列にトグルを Bootstrap 5 のスイッチ風チェックボックス に表示して、「InOut」列の値、true、false を切り替える方法を教えてください。

内容

了解です。
前回のコードをさらに改良し、Bootstrap 5 スイッチに アイコン(+/−)付きで入金/出金を直感的に切り替えられるバージョンにします。
また、アクセシビリティ向上のため aria-label を追加し、初期状態もモデル値に応じて反映されるようにしています。

1. モデル

Csharp
public class Transaction { public int Id { get; set; } // 入金(true) / 出金(false) public bool InOut { get; set; } public decimal Amount { get; set; } }

2. コントローラー

Csharp
using Microsoft.AspNetCore.Mvc; public class TransactionsController : Controller { [HttpGet] public IActionResult Create() { // 初期値を設定する場合(例: デフォルトは入金) var model = new Transaction { InOut = true }; return View(model); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Create(Transaction model) { if (ModelState.IsValid) { // model.InOut が true/false で取得可能 // DB保存処理など return RedirectToAction(nameof(Index)); } return View(model); } }

3. Create.cshtml(アイコン付きスイッチ)

Cshtml
@model Transaction @{ ViewData["Title"] = "Create Transaction"; } <h2>Create Transaction</h2> <form asp-action="Create" method="post"> <div class="mb-3 form-check form-switch"> <input asp-for="InOut" class="form-check-input" type="checkbox" id="InOutSwitch" aria-label="入金/出金切り替え" /> <label class="form-check-label fw-bold d-flex align-items-center gap-1" for="InOutSwitch"> <span id="InOutIcon"></span> <span id="InOutText"></span> </label> </div> <div class="mb-3"> <label asp-for="Amount" class="form-label"></label> <input asp-for="Amount" class="form-control" /> <span asp-validation-for="Amount" class="text-danger"></span> </div> <button type="submit" class="btn btn-primary">登録</button> </form> @section Scripts { <partial name="_ValidationScriptsPartial" /> <style> .switch-income { color: #198754; /* 緑 */ } .switch-expense { color: #dc3545; /* 赤 */ } </style> <script> const inOutSwitch = document.getElementById('InOutSwitch'); const icon = document.getElementById('InOutIcon'); const text = document.getElementById('InOutText'); const label = document.querySelector('label[for="InOutSwitch"]'); function updateSwitchUI() { if (inOutSwitch.checked) { icon.textContent = '+'; text.textContent = '入金'; label.classList.add('switch-income'); label.classList.remove('switch-expense'); } else { icon.textContent = '−'; text.textContent = '出金'; label.classList.add('switch-expense'); label.classList.remove('switch-income'); } } inOutSwitch.addEventListener('change', updateSwitchUI); updateSwitchUI(); // 初期表示 </script> }

改良点

  1. アイコン追加
    • 入金時は「+」、出金時は「−」を表示。
  2. 色分け
    • 入金(true)時は緑色、出金(false)時は赤色。
  3. アクセシビリティ対応
    • aria-label を追加してスクリーンリーダー対応。
  4. 初期状態反映
    • モデルの InOut 値に応じて初期表示を切り替え。

このバージョンなら、見た目・操作性・アクセシビリティのすべてで実用的なトグルスイッチになります。

もし希望があれば、このスイッチを アニメーション付き にして、切り替え時に色やアイコンがスムーズに変わるようにもできます。
次はそのアニメーション付きバージョンも作りますか?

Powered by Froala Editor

添付画像

画像はありません
Genreのカテゴリ-名
Views
編集 | 記事一覧