了解です。
ASP.NET Core MVC で ドロップダウン <select> と ユーザー入力 <input> を併用し、
「その他」選択時だけ入力欄を表示 → DB 登録まで行う Create アクション の実装例を示します。
以下は 完全動作可能なサンプル です。
1. モデル定義
using System.ComponentModel.DataAnnotations;
public class Category
{
public int Id { get; set; }
[Required(ErrorMessage = "カテゴリを選択してください")]
public string SelectedCategory { get; set; }
// 「その他」入力用
public string OtherCategory { get; set; }
}
2. ViewModel(DB登録用に加工)
public class CategoryViewModel
{
public Category Category { get; set; }
public List<string> CategoryList { get; set; }
}
3. Controller
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
public class CategoryController : Controller
{
private readonly ApplicationDbContext _context;
public CategoryController(ApplicationDbContext context)
{
_context = context;
}
// GET: Create
public IActionResult Create()
{
var vm = new CategoryViewModel
{
Category = new Category(),
CategoryList = new List<string> { "食品", "衣類", "家電", "その他" }
};
return View(vm);
}
// POST: Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CategoryViewModel vm)
{
if (ModelState.IsValid)
{
// 「その他」が選択されている場合は OtherCategory を使用
var categoryName = vm.Category.SelectedCategory == "その他"
? vm.Category.OtherCategory
: vm.Category.SelectedCategory;
var entity = new Category
{
SelectedCategory = categoryName
};
_context.Add(entity);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
// 再表示用にカテゴリリストを再設定
vm.CategoryList = new List<string> { "食品", "衣類", "家電", "その他" };
return View(vm);
}
public IActionResult Index()
{
var list = _context.Set<Category>();
return View(list);
}
}
4. View (Create.cshtml)
@model CategoryViewModel
@{
ViewData["Title"] = "Create";
}
<h2>Create</h2>
<form asp-action="Create" method="post">
<div class="form-group">
<label>カテゴリ</label>
<select asp-for="Category.SelectedCategory" class="form-control" id="categorySelect">
<option value="">-- 選択してください --</option>
@foreach (var item in Model.CategoryList)
{
<option value="@item">@item</option>
}
</select>
<span asp-validation-for="Category.SelectedCategory" class="text-danger"></span>
</div>
<div class="form-group" id="otherCategoryDiv" style="display:none;">
<label>その他カテゴリ</label>
<input asp-for="Category.OtherCategory" class="form-control" />
</div>
<button type="submit" class="btn btn-primary">登録</button>
</form>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
<script>
document.getElementById("categorySelect").addEventListener("change", function () {
var otherDiv = document.getElementById("otherCategoryDiv");
if (this.value === "その他") {
otherDiv.style.display = "block";
} else {
otherDiv.style.display = "none";
document.querySelector("#otherCategoryDiv input").value = "";
}
});
</script>
}
5. ポイント
- ViewModel を使って、カテゴリリストと入力データをまとめて View に渡す。
- JavaScript で
<select> の値が "その他" のときだけ <input> を表示。 - Controller 側で
"その他" 選択時は OtherCategory の値を DB に保存。 - ModelState を使ってバリデーションを行い、再表示時にカテゴリリストを再設定。
✅ この構成なら、
- 「その他」選択時だけ入力欄が表示される
- 入力値は Create アクションで受け取り、DB に登録できる
- 再描画時もカテゴリリストが保持される
もし希望があれば、このサンプルを Entity Framework Core のマイグレーション込みで動く完全プロジェクト構成 にしてお渡しできますが、そうしますか?
そうすればコピペで即動作確認できます。
Powered by Froala Editor