了解です。
ASP.NET Core MVC のフォームで <select> に「その他」オプションを用意し、それが選択されたときだけ <input> テキストボックスを表示する方法を、JavaScript を使って実装する例を示します。
以下は 完全動作するサンプル です。
1. モデル
// Models/CategoryViewModel.cs
using System.ComponentModel.DataAnnotations;
public class CategoryViewModel
{
[Required]
public string SelectedCategory { get; set; }
public string OtherCategory { get; set; }
}
2. コントローラ
// Controllers/HomeController.cs
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
public class HomeController : Controller
{
public IActionResult Index()
{
ViewBag.Categories = new List<string> { "食品", "衣類", "家電", "その他" };
return View(new CategoryViewModel());
}
[HttpPost]
public IActionResult Index(CategoryViewModel model)
{
if (ModelState.IsValid)
{
string category = model.SelectedCategory == "その他"
? model.OtherCategory
: model.SelectedCategory;
ViewBag.Message = $"選択されたカテゴリ: {category}";
}
ViewBag.Categories = new List<string> { "食品", "衣類", "家電", "その他" };
return View(model);
}
}
3. ビュー (Razor)
@model CategoryViewModel
@{
ViewData["Title"] = "カテゴリ選択フォーム";
}
<h2>カテゴリ選択フォーム</h2>
<form asp-action="Index" method="post">
<div>
<label>カテゴリ:</label>
<select id="categorySelect" asp-for="SelectedCategory" name="SelectedCategory" required>
<option value="">--選択してください--</option>
@foreach (var cat in ViewBag.Categories as List<string>)
{
<option value="@cat" @(Model.SelectedCategory == cat ? "selected" : "")>@cat</option>
}
</select>
</div>
<div id="otherCategoryDiv" style="display:none; margin-top:10px;">
<label>その他のカテゴリ:</label>
<input type="text" asp-for="OtherCategory" name="OtherCategory" />
</div>
<button type="submit">送信</button>
</form>
@if (ViewBag.Message != null)
{
<p style="color:green">@ViewBag.Message</p>
}
@section Scripts {
<script>
document.addEventListener("DOMContentLoaded", function () {
const select = document.getElementById("categorySelect");
const otherDiv = document.getElementById("otherCategoryDiv");
function toggleOtherInput() {
if (select.value === "その他") {
otherDiv.style.display = "block";
} else {
otherDiv.style.display = "none";
// 入力値をクリア
otherDiv.querySelector("input").value = "";
}
}
// 初期表示時の状態反映
toggleOtherInput();
// 選択変更時のイベント
select.addEventListener("change", toggleOtherInput);
});
</script>
}
4. 動作仕様
<select> に「その他」が選ばれたときだけ、<input> が表示されます。- それ以外の選択肢では
<input> は非表示になり、値もクリアされます。 - サーバー側では「その他」が選ばれた場合のみ
OtherCategory の値を使用します。
✅ この方法は ASP.NET Core MVC の標準的なフォーム構築方法に準拠しており、JavaScript は純粋な DOM 操作で軽量に実装しています。
✅ jQuery などの外部ライブラリは不要です。
もしご希望であれば、このサンプルを jQuery 版 に書き換えて、より短いコードにすることもできますが、
このままでも十分軽量で保守性が高いです。
このあと、必要であれば 「その他」選択時に必須入力チェックをクライアント側でも行うバリデーション付きバージョン を作ることもできますが、作成しますか?
Powered by Froala Editor