了解です。
ASP.NET Core MVC の Create ビューで、InOut(bool型)を Bootstrap 5 のスイッチ風トグルとして表示し、
true(入金)/false(出金)を切り替える方法を、完全なコード例で説明します。
1. モデル
public class Transaction
{
public int Id { get; set; }
// 入金(true) / 出金(false)
public bool InOut { get; set; }
public decimal Amount { get; set; }
}
2. コントローラー(Create アクション)
using Microsoft.AspNetCore.Mvc;
public class TransactionsController : Controller
{
[HttpGet]
public IActionResult Create()
{
return View();
}
[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(Bootstrap 5 スイッチ風チェックボックス)
@model Transaction
@{
ViewData["Title"] = "Create Transaction";
}
<h2>Create Transaction</h2>
<form asp-action="Create" method="post">
<div class="mb-3 form-check form-switch">
<!-- asp-for で bool 型をバインド -->
<input asp-for="InOut" class="form-check-input" type="checkbox" id="InOutSwitch" />
<label class="form-check-label" for="InOutSwitch">
入金 / 出金
</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" />
<script>
// チェック状態に応じてラベルを動的に変更
const inOutSwitch = document.getElementById('InOutSwitch');
const label = document.querySelector('label[for="InOutSwitch"]');
function updateLabel() {
label.textContent = inOutSwitch.checked ? '入金' : '出金';
}
inOutSwitch.addEventListener('change', updateLabel);
updateLabel(); // 初期表示
</script>
}
4. ポイント
form-check form-switch クラスで Bootstrap 5 のスイッチ風に。asp-for="InOut" を使うことで、POST 時に bool 値が自動的にモデルにバインドされます。- JavaScript でラベルを動的に「入金」/「出金」に切り替え。
- 初期状態は
false(出金)ですが、モデルの値に応じてチェック状態が反映されます。
5. 動作イメージ
- スイッチが ON →
InOut = true(入金) - スイッチが OFF →
InOut = false(出金) - フォーム送信時にそのままモデルにバインドされます。
もし希望があれば、このスイッチを 「入金」緑色/「出金」赤色 に色分けするカスタムCSS付きバージョンも作れますが、
まずはこのコードで Bootstrap 5 標準スイッチとして動作します。
このまま作ると、CreateView でトグルを切り替えて bool 値を送信できる完全な形になります。
次に、色分けやアイコン付きにする拡張版も作りますか?
Powered by Froala Editor