記事詳細


投稿日
2026年09月05日22時00分
タイトル

ASP.NET Core MVC: Index Viewの、行の中でitem.InOutが“true” item.ItemNameが"現在残高"、そしてitem.Amountが“0”場合の行がある場合に、SweetAlert2 を使って、Editページに遷移する方法

内容
@model IEnumerable<YourNamespace.Models.YourModel>

@{
    // 条件に一致する最初の行を取得
    var targetItem = Model.FirstOrDefault(x =>
        x.InOut == true &&
        x.ItemName == "現在残高" &&
        x.Amount == 0
    );
}

<!-- SweetAlert2 CDN -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

@if (targetItem != null)
{
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            Swal.fire({
                title: '金額が未入力です',
                text: 'Editボタンをクリックして金額を入力して下さい',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes',
                cancelButtonText: 'No',
                allowOutsideClick: false, // モーダル外クリックで閉じない
                allowEscapeKey: false     // ESCキーで閉じない
            }).then((result) => {
                if (result.isConfirmed) {
                    // Yesが押された場合 → Editページへ遷移
                    window.location.href = '@Url.Action("Edit", "YourController", new { id = targetItem.Id })';
                } else if (result.dismiss === Swal.DismissReason.cancel) {
                    // Noが押された場合 → 何もしない
                    console.log("ユーザーが編集をキャンセルしました");
                }
            });
        });
    </script>
}

改良点

  • 条件抽出を FirstOrDefault のラムダ式で簡潔化
    → 最初に該当する行だけを取得。
  • モーダルの操作制限追加
    → allowOutsideClick と allowEscapeKey を false にして、必ず Yes/No を選択させる。
  • キャンセル時のログ出力
    → デバッグや動作確認に便利。
  • 変数名を targetItem に変更
    → 意味が明確になり可読性向上。

Powered by Froala Editor

添付画像

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