記事詳細


投稿日
2026年08月04日13時32分
タイトル

ASP.NET Core MVC: 入力フォームに於いて、ViewData[Category]のドロップダウン<select>とユーザー入力<input>両機能を併用して、、DB登録まで含めたCreateアクションメソッドにそのデータを送信する方法を教えててください。「その他」選択時だけ入力欄

内容

了解です。
ASP.NET Core MVC で ドロップダウン(ViewData["Category"]) と ユーザー入力欄 を併用し、
「その他」選択時だけ入力欄を表示し、DB登録まで行う Create アクションの実装例を示します。

1. モデル定義

Csharp
// Models/Product.cs using System.ComponentModel.DataAnnotations; public class Product { public int Id { get; set; } [Required] public string Category { get; set; } = string.Empty; public string? OtherCategory { get; set; } }

2. コントローラー

Csharp
// Controllers/ProductsController.cs using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; public class ProductsController : Controller { private readonly ApplicationDbContext _context; public ProductsController(ApplicationDbContext context) { _context = context; } // GET: Create public IActionResult Create() { ViewData["Category"] = new SelectList(new[] { "食品", "衣類", "家電", "その他" }); return View(); } // POST: Create [HttpPost] [ValidateAntiForgeryToken] public IActionResult Create(Product product) { if (product.Category == "その他" && string.IsNullOrWhiteSpace(product.OtherCategory)) { ModelState.AddModelError("OtherCategory", "その他を選択した場合は入力してください。"); } if (ModelState.IsValid) { // 「その他」選択時は OtherCategory を Category に反映 if (product.Category == "その他" && !string.IsNullOrWhiteSpace(product.OtherCategory)) { product.Category = product.OtherCategory; } _context.Add(product); _context.SaveChanges(); return RedirectToAction(nameof(Index)); } // 再描画用に ViewData を再設定 ViewData["Category"] = new SelectList(new[] { "食品", "衣類", "家電", "その他" }, product.Category); return View(product); } }

3. ビュー(Razor)

Cshtml
@model Product @{ ViewData["Title"] = "Create"; } <h2>Create</h2> <form asp-action="Create" method="post"> <div class="form-group"> <label asp-for="Category"></label> <select asp-for="Category" class="form-control" asp-items="@(ViewData["Category"] as SelectList)" id="categorySelect"> </select> <span asp-validation-for="Category" class="text-danger"></span> </div> <div class="form-group" id="otherCategoryDiv" style="display:none;"> <label asp-for="OtherCategory">その他のカテゴリ</label> <input asp-for="OtherCategory" class="form-control" /> <span asp-validation-for="OtherCategory" class="text-danger"></span> </div> <button type="submit" class="btn btn-primary">登録</button> </form> @section Scripts { <partial name="_ValidationScriptsPartial" /> <script> const categorySelect = document.getElementById("categorySelect"); const otherDiv = document.getElementById("otherCategoryDiv"); function toggleOtherInput() { if (categorySelect.value === "その他") { otherDiv.style.display = "block"; } else { otherDiv.style.display = "none"; document.querySelector("[name='OtherCategory']").value = ""; } } categorySelect.addEventListener("change", toggleOtherInput); toggleOtherInput(); // 初期表示時 </script> }

4. 動作の流れ

  1. Create GET
    • ViewData["Category"] にカテゴリ一覧を設定し、ビューに渡す。
  2. ビュー
    • <select> でカテゴリ選択。
    • 「その他」選択時のみ <input> が表示される(JavaScriptで制御)。
  3. Create POST
    • 「その他」選択時は OtherCategory の入力必須チェック。
    • DB登録時は Category に OtherCategory の値を反映。
  4. DB保存
    • _context.SaveChanges() で永続化。

✅ この方法なら、

  • ViewData + SelectList を使ったドロップダウン
  • 「その他」選択時だけ表示される入力欄
  • 入力必須バリデーション
  • DB登録までの一連の流れ
    が実現できます。

もし希望があれば、このコードを 非同期(AJAX)送信対応版 に書き換えて、ページリロードなしで登録できる形にもできますが、そうしますか?

Powered by Froala Editor

添付画像

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