記事詳細


投稿日
2026年08月11日18時14分
タイトル

ASP.NET Core MVC: Viewの” <select asp-for="PaymentTypeId" class ="form-control" asp-items="ViewBag.PaymentTypeId"></select>”のリストのvalueはTypeIdですが表示データ(TypeName)を登録前に取得する方法を教えてください。

内容

なるほど、
<select asp-for="PaymentTypeId" asp-items="ViewBag.PaymentTypeId"> の場合、value は TypeId ですが、登録前に選択された TypeName を取得したいということですね。

ASP.NET Core MVC では、サーバー側でも**クライアント側(JavaScript)**でも取得可能です。
以下に両方の方法を示します。

1. クライアント側(JavaScriptで取得)

登録(POST)前にブラウザで選択中の表示テキスト(TypeName)を取得できます。

Html
<select asp-for="PaymentTypeId" class="form-control" asp-items="ViewBag.PaymentTypeId" id="PaymentTypeId"></select> <script> document.getElementById("PaymentTypeId").addEventListener("change", function () { // 選択中の option の表示テキスト(TypeName) let selectedText = this.options[this.selectedIndex].text; let selectedValue = this.value; // TypeId console.log("選択された TypeId:", selectedValue); console.log("選択された TypeName:", selectedText); }); </script>

これで、フォーム送信前に TypeName を取得して別の hidden フィールドに入れることも可能です。

2. サーバー側(Controllerで取得)

フォーム送信時に PaymentTypeId しか送られませんが、DBやリストから TypeName を引けます。

Csharp
[HttpPost] public IActionResult Create(MyViewModel model) { // model.PaymentTypeId が送信された値 var typeName = _context.PaymentTypes .Where(t => t.TypeId == model.PaymentTypeId) .Select(t => t.TypeName) .FirstOrDefault(); // typeName を使って処理 ... }

3. Hiddenフィールドで一緒に送信する方法

JavaScriptで選択時に TypeName を hidden にセットして送信する方法です。

Html
<select asp-for="PaymentTypeId" class="form-control" asp-items="ViewBag.PaymentTypeId" id="PaymentTypeId"></select> <input type="hidden" name="PaymentTypeName" id="PaymentTypeName" /> <script> document.getElementById("PaymentTypeId").addEventListener("change", function () { document.getElementById("PaymentTypeName").value = this.options[this.selectedIndex].text; }); </script>

Controller 側では PaymentTypeName も受け取れます。

✅ まとめ

  • 画面上で即取得 → JavaScriptで selectedIndex の .text を取る
  • サーバーで取得 → PaymentTypeId からDBやリストで TypeName を引く
  • 両方送信 → hidden フィールドにセットしてPOST

もし「登録前に画面上で TypeName を別の項目に表示したい」なら、
JavaScriptでの方法(1)が一番シンプルです。

必要であれば、選択したTypeNameを即座に別の入力欄やラベルに反映するサンプルも作れますが、それも載せますか?
そうすれば登録前にユーザーにも確認できます。

Powered by Froala Editor

添付画像

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