なるほど、やりたいことは以下の流れですね。
- Create.cshtml にアクセスした時点で、
DB の Payments テーブルに SubjectNameId = 14 のデータが存在するかをサーバー側で判定。 - 存在しない場合、SweetAlert2 のモーダルを表示して
「繰越金額を入力してください」+ Yes/No ボタンを出す。 - Yes を押したら
<select asp-for="SubjectNameId"> に 14 をセットし、
<input asp-for="Amount"> に金額を入力できるようにする。
実装例
1. Controller 側でフラグを渡す
// PaymentsController.cs
public IActionResult Create()
{
// DBにSubjectNameId=14が存在するかチェック
bool needsCarryOver = !_context.Payments.Any(p => p.SubjectNameId == 14);
ViewBag.NeedsCarryOver = needsCarryOver;
// ViewBag.SubjectNameId のSelectListをセット
ViewBag.SubjectNameId = new SelectList(_context.SubjectNames, "Id", "Name");
return View();
}
2. Create.cshtml 側
@model YourNamespace.Models.Payment
@{
ViewData["Title"] = "Create";
}
<h2>Create</h2>
<form asp-action="Create">
<div class="form-group">
<label asp-for="SubjectNameId" class="control-label"></label>
<select asp-for="SubjectNameId" class="form-control" asp-items="ViewBag.SubjectNameId"></select>
</div>
<div class="form-group">
<label asp-for="Amount" class="control-label"></label>
<input asp-for="Amount" class="form-control" />
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
@section Scripts {
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {
var needsCarryOver = @((ViewBag.NeedsCarryOver ?? false).ToString().ToLower());
if (needsCarryOver) {
Swal.fire({
title: '“繰越金額”を入力して下さい',
icon: 'info',
showCancelButton: true,
confirmButtonText: 'Yes',
cancelButtonText: 'No'
}).then((result) => {
if (result.isConfirmed) {
// SubjectNameId を 14 にセット
document.querySelector('[name="SubjectNameId"]').value = 14;
// Amount フィールドにフォーカス
document.querySelector('[name="Amount"]').focus();
}
});
}
});
</script>
}
3. ポイント
- DBチェックは必ずサーバー側で行う
→ クライアント側だけで判定すると改ざんされる可能性があるため。 - SweetAlert2 の
then 内で <select> の値を 14 にセット。 <input asp-for="Amount"> はそのままユーザーが入力可能。- Yes を押さなかった場合は何も変更せず通常のフォーム状態。
4. 動作イメージ
Payments に SubjectNameId = 14 が存在しない場合のみモーダルが出る。- Yes →
<select> が自動的に「14」に切り替わり、金額入力欄にカーソルが移動。 - No → 何もせず通常の入力。
もし希望があれば、この SweetAlert2 のモーダルで 金額入力欄も直接モーダル内に表示して、そのままフォームに反映する バージョンも作れます。
そうするとページ遷移なしでモーダル内で金額を入力できます。
このままページ内で入力させる方法と、モーダル内で直接入力させる方法、どちらで進めますか?
後者だとユーザー体験がよりスムーズになります。