なるほど、
ASP.NET Core MVC の Create ビューで、bool 型の InOut 列を「入金(true)」「出金(false)」としてボタンで切り替えたい、ということですね。
これは フォーム送信前に JavaScript で hidden フィールドの値を切り替える 方法がシンプルで実装しやすいです。
以下に 完全な動作例 を示します。
1. モデル
public class Transaction
{
public int Id { get; set; }
// 入金(true) / 出金(false)
public bool InOut { get; set; }
public decimal Amount { get; set; }
}
2. コントローラー
using Microsoft.AspNetCore.Mvc;
public class TransactionsController : Controller
{
[HttpGet]
public IActionResult Create()
{
return View(new Transaction { InOut = true }); // 初期値は入金
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Transaction model)
{
if (ModelState.IsValid)
{
// DB保存処理など
// _context.Transactions.Add(model);
// _context.SaveChanges();
return RedirectToAction(nameof(Index));
}
return View(model);
}
}
3. Create.cshtml(ビュー)
@model Transaction
@{
ViewData["Title"] = "Create Transaction";
}
<h2>Create Transaction</h2>
<form asp-action="Create" method="post">
@Html.AntiForgeryToken()
<!-- hiddenでInOutを送信 -->
<input type="hidden" asp-for="InOut" id="InOut" />
<div class="form-group">
<label>入出金</label><br />
<button type="button" id="toggleBtn" class="btn btn-success">
入金
</button>
</div>
<div class="form-group">
<label asp-for="Amount"></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 {
<script>
document.addEventListener("DOMContentLoaded", function () {
const inOutField = document.getElementById("InOut");
const toggleBtn = document.getElementById("toggleBtn");
// 初期表示
updateButton();
toggleBtn.addEventListener("click", function () {
// true/falseを切り替え
inOutField.value = (inOutField.value === "true") ? "false" : "true";
updateButton();
});
function updateButton() {
if (inOutField.value === "true") {
toggleBtn.textContent = "入金";
toggleBtn.classList.remove("btn-danger");
toggleBtn.classList.add("btn-success");
} else {
toggleBtn.textContent = "出金";
toggleBtn.classList.remove("btn-success");
toggleBtn.classList.add("btn-danger");
}
}
});
</script>
}
4. 動作仕様
InOut は hidden フィールドでフォーム送信時に値が送られます。- ボタンを押すと JavaScript で
true ⇔ false を切り替えます。 - ボタンの表示テキストと色も切り替わります(入金=緑、出金=赤)。
- サーバー側では
bool InOut として受け取れます。
5. メリット
- フォーム送信前に切り替えられるので、サーバー側で特別な処理は不要。
asp-for を使っているのでモデルバインディングが自動で行われます。- 入金/出金の UI が直感的。
もし希望があれば、このボタンを トグルスイッチ風 にして、Bootstrap や Tailwind で見た目をもっと良くすることもできます。
この方法なら、CreateView 内で「入金(true)」「出金(false)」を簡単に切り替えられますが、
ご希望であれば サーバー側でボタンごとに別の値を送信する方法(2つの submit ボタン)も実装例を出せます。
要望があれば、次に 2つの送信ボタン方式 のコードも提示できますが、この hidden+JS トグル方式が一番シンプルです。
このままそのコードを出しますか?
Powered by Froala Editor