記事詳細


投稿日
2026年08月31日07時31分
タイトル

ASP.NET Core MVC: Create.cshtmlに<input type="file" name="upFile" id="upFile" class="form-control" accept="image/*"/>にファイルを挿入して、そのファイルの「拡張子を除いた名前」を<input asp-for="CourseName" class="form-control" />に設定する際にその「拡張子を除いた名前」が、ControllerにあるViewData["SubjectNameId"] = new SelectList(_context.SubjectNames, "SubjectNameId", "CourseName");のリスト内にあれば「同名のデータが既ににあります」というSweetAlert2 を使ったモーダルダイアログを表示して送信を停止するコードを教えてください。

内容

OK — あなたの要件は、
ASP.NET Core MVC の Create.cshtml でファイルを選択したときに、

  1. ファイル名(拡張子なし)を <input asp-for="CourseName" /> に自動設定
  2. その名前が Controller から渡されたリストViewData["SubjectNameId"])に存在する場合、
    SweetAlert2 で「同名のデータが既にあります」と表示し、送信を止める

というものですね。

以下に 完全動作するサンプルコード を示します。
(SweetAlert2 は CDN から読み込み、JavaScript 側でチェックします)

Controller 側(例)

Csharp
// GET: Courses/Create public IActionResult Create() { // 既存のコース名リストを取得 var existingNames = _context.SubjectNames .Select(s => s.CourseName) .ToList(); // ViewData に SelectList(フォーム用)と既存名リスト(JS用)を渡す ViewData["SubjectNameId"] = new SelectList(_context.SubjectNames, "SubjectNameId", "CourseName"); ViewBag.ExistingCourseNames = existingNames; return View(); }

Create.cshtml

Cshtml
@model YourNamespace.Models.Course @{ ViewData["Title"] = "Create"; // 既存コース名リストを JSON に変換して JS に渡す var existingNamesJson = System.Text.Json.JsonSerializer.Serialize(ViewBag.ExistingCourseNames); } <!-- SweetAlert2 CDN --> <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script> <h2>Create</h2> <form asp-action="Create" id="createForm" enctype="multipart/form-data"> <div class="form-group"> <label for="upFile">Upload File</label> <input type="file" name="upFile" id="upFile" class="form-control" accept="image/*" /> </div> <div class="form-group"> <label asp-for="CourseName"></label> <input asp-for="CourseName" class="form-control" /> <span asp-validation-for="CourseName" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="SubjectNameId"></label> <select asp-for="SubjectNameId" class="form-control" asp-items="@(ViewData["SubjectNameId"] as SelectList)"> </select> </div> <button type="submit" class="btn btn-primary">Create</button> </form> @section Scripts { <partial name="_ValidationScriptsPartial" /> <script> // 既存コース名リスト(小文字化して比較用) const existingNames = @Html.Raw(existingNamesJson); const lowerExistingNames = existingNames.map(n => n.toLowerCase()); const fileInput = document.getElementById('upFile'); const courseNameInput = document.getElementById('CourseName'); const form = document.getElementById('createForm'); // ファイル選択時に拡張子を除いた名前を CourseName にセット fileInput.addEventListener('change', function () { if (this.files.length > 0) { const fileName = this.files[0].name; const nameWithoutExt = fileName.replace(/\.[^/.]+$/, ""); // 拡張子除去 courseNameInput.value = nameWithoutExt; } }); // フォーム送信時に重複チェック form.addEventListener('submit', function (e) { const enteredName = courseNameInput.value.trim().toLowerCase(); if (lowerExistingNames.includes(enteredName)) { e.preventDefault(); // 送信停止 Swal.fire({ icon: 'error', title: '同名のデータが既にあります', text: '別の名前を入力してください。', confirmButtonText: 'OK' }); } }); </script> }

ポイント

  1. Controller

    • ViewBag.ExistingCourseNames に既存のコース名リストを渡す
    • これを JSON にして JavaScript 側で利用
  2. JavaScript

    • ファイル選択時に nameWithoutExt を <input asp-for="CourseName" /> に自動設定
    • 送信時に既存名リストと比較し、重複があれば SweetAlert2 で警告して送信を中止
  3. SweetAlert2

    • CDN から読み込み
    • Swal.fire({...}) でモーダル表示

✅ この方法なら サーバー側のデータをクライアントで事前チェック でき、
ユーザーは送信前に重複を知ることができます。

もし希望があれば、このチェックを サーバー側でも二重に行う安全対策付きバージョン にできますが、
それも追加しますか?
そうすれば、JavaScript無効化や改ざん時にも安全です。

Powered by Froala Editor

添付画像

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