質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Entity Framework

Entity Frameworkは、.NET Framework 3.5より追加されたデータアクセス技術。正式名称は「ADO.NET Entity Framework」です。データベースエンジンに依存しておらず、データプロバイダの変更のみで様々なデータベースに対応できます。

C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

ASP.NET MVC Framework

ASP.NET MVC Frameworkは、MVCパターンをベースとした、マイクロソフトのウェブアプリケーション開発用のフレームワークです。

Q&A

解決済

3回答

9831閲覧

ASP.NET MVCでDropdownlistの初期値設定方法(DBから取得)

blackdifferent

総合スコア25

Entity Framework

Entity Frameworkは、.NET Framework 3.5より追加されたデータアクセス技術。正式名称は「ADO.NET Entity Framework」です。データベースエンジンに依存しておらず、データプロバイダの変更のみで様々なデータベースに対応できます。

C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

ASP.NET MVC Framework

ASP.NET MVC Frameworkは、MVCパターンをベースとした、マイクロソフトのウェブアプリケーション開発用のフレームワークです。

0グッド

0クリップ

投稿2018/12/03 01:13

こんにちわ!
ASP.NET MVC Frameworkで勤務表を作成しています(Visualstudio 2017, C#,entity framework)。
DropdownlistでDBのテーブルからリストを表示し、選択項目をDBの別のテーブルへ保存する機能のところで困っています。
一応以下のコードで選択肢表示と選択項目の保存が出来るようになりましたが、初期値の表示が出来ません。
選択した項目はInt型でDBに保存して、選択項目のテーブルでString型に置き換えて表示したいです。
よろしくお願いします。

コントローラ:

using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using Kintai_CS_.Models; namespace Kintai_CS_.Controllers { public class TKintaisController : Controller { private mvcdbEntities db = new mvcdbEntities(); // GET: TKintais public ActionResult Index() { // 選択ボックスのオプションを準備 ViewBag.ServerOptions = db.TSituation.Select(s => new SelectListItem { Text = s.situation, Value = s.id.ToString() }); return View(db.TKintai.ToList()); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Index(List<TKintai> products) { foreach(var kintai in products) { TKintai sv_product = db.TKintai.Find(kintai.id); sv_product.open = kintai.open; sv_product.close = kintai.close; sv_product.rest = kintai.rest; sv_product.situation = kintai.situation; sv_product.remark = kintai.remark; if (kintai.open != null && kintai.close != null && kintai.rest != null) { kintai.worktime = kintai.close - kintai.open - kintai.rest; kintai.overtime = kintai.worktime - TimeSpan.FromHours(8); } } db.SaveChanges(); return RedirectToAction("Index"); } } }

ビュー:

@model List<Kintai_CS_.Models.TKintai> @{ /**/ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Index</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <table class="table"> <tr> <th> id </th> <th> week </th> <th> open </th> <th> close </th> <th> rest </th> <th> worktime </th> <th> overtime </th> <th> situation </th> <th> 補助 </th> <th> remark </th> </tr> @for (int i = 0; i < Model.Count; i++) { int idx = i; <tr> <td> @Html.DisplayFor(model => model[idx].id) @Html.HiddenFor(model => model[idx].id) </td> <td> @Html.DisplayFor(model => model[idx].week) @Html.HiddenFor(model => model[idx].week) </td> <td> @Html.EditorFor(model => model[idx].open, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model[idx].open, "", new { @class = "text-danger" }) </td> <td> @Html.EditorFor(model => model[idx].close, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model[idx].close, "", new { @class = "text-danger" }) </td> <td> @Html.EditorFor(model => model[idx].rest, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model[idx].rest, "", new { @class = "text-danger" }) </td> <td> @Html.DisplayFor(model => model[idx].worktime) @Html.HiddenFor(model => model[idx].worktime) </td> <td> @Html.DisplayFor(model => model[idx].overtime) @Html.HiddenFor(model => model[idx].overtime) </td> <td> ** @Html.DropDownListFor(model => model[idx].situation, (IEnumerable<SelectListItem>)ViewBag.ServerOptions, "選択してください", new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model[idx].situation, "", new { @class = "text-danger" })** </td> <td style="width: 66px"> <nobr> <button type="button" onclick="location.href='@Url.Action("BtnClick","Kintai")'">定</button> </nobr> </td> <td> @Html.EditorFor(model => model[idx].remark, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model[idx].remark, "", new { @class = "text-danger" }) </td> </tr> } </table> <p> <input type="submit" value="更新" /> </p> }

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答3

0

普通に考えると(あくまでも自分的にですが)こんな感じで実装するという例を書いておきます。質問者さんの DB の構造は分かりませんし、アップしてあるコードに応用できるかは分かりませんが。

以下は Microsoft が提供しているサンプルデータベース Northwind から Visual Studio のウィザードを利用して作った EDM の一部分です。

イメージ説明

Products テーブルの SupplierID は数字です。Products テーブルのレコードを Edit する際、SupplierID はテキストボックスに数字を表示するのではなく、ドロップダウンリストに供給者名を文字列で表示するとします。以下のブラウザ画面のような感じです(ドロップダウンリストを開いたところです)。

イメージ説明

一番上の EDM の画像に示すように Northwind には Products テーブル他に Suppliers というテーブルがあり、その主キー SupplierID から Products テーブルの SupplierID に外部キー制約が張られています。

EDM 画像の Products というのが質問者さんのケースでは TKintai で、SupplierID が situation に該当すると考えてください。質問者さんの DB に、Suppliers テーブルに該当する situation テーブルというのが存在するのかどうか分かりませんが、下のコードはそれがあることが前提です。

上のブラウザ画面のコードは以下の通りです。ViewBag を使って SelectList を View に渡し、@Html.DropDownList を使って表示しているところがポイントです。

質問者さんの DB に、Suppliers テーブルに該当する situation テーブルというのが存在しなければ、何らかの手段で db.Suppliers と同等なオブジェクトを作成して使うことになると思います。

Controller / Action Method

using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using Mvc5App; namespace Mvc5App.Controllers { public class ProductsController : Controller { private NORTHWINDEntities db = new NORTHWINDEntities(); // ・・・中略・・・ // GET: Products/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Products products = db.Products.Find(id); if (products == null) { return HttpNotFound(); } ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", products.CategoryID); ViewBag.SupplierID = new SelectList(db.Suppliers, "SupplierID", "CompanyName", products.SupplierID); return View(products); } // POST: Products/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "ProductID,ProductName,SupplierID,CategoryID,QuantityPerUnit,UnitPrice,UnitsInStock,UnitsOnOrder,ReorderLevel,Discontinued")] Products products) { if (ModelState.IsValid) { db.Entry(products).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", products.CategoryID); ViewBag.SupplierID = new SelectList(db.Suppliers, "SupplierID", "CompanyName", products.SupplierID); return View(products); } // ・・・中略・・・ } }

View

@model Mvc5App.Products @{ ViewBag.Title = "Edit"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Edit</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Products</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(model => model.ProductID) <div class="form-group"> @Html.LabelFor(model => model.ProductName, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.ProductName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.ProductName, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.SupplierID, "SupplierID", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownList("SupplierID", null, htmlAttributes: new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.SupplierID, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.CategoryID, "CategoryID", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownList("CategoryID", null, htmlAttributes: new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.CategoryID, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.QuantityPerUnit, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.QuantityPerUnit, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.QuantityPerUnit, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.UnitPrice, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.UnitPrice, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.UnitPrice, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.UnitsInStock, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.UnitsInStock, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.UnitsInStock, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.UnitsOnOrder, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.UnitsOnOrder, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.UnitsOnOrder, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.ReorderLevel, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.ReorderLevel, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.ReorderLevel, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Discontinued, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> <div class="checkbox"> @Html.EditorFor(model => model.Discontinued) @Html.ValidationMessageFor(model => model.Discontinued, "", new { @class = "text-danger" }) </div> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Save" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }

上記コードは以下の記事の手順で全て Visual Stidio 2015 に自動生成させたものをコピペしただけです。一度、このように作ってみてはいかがですか? 今後の参考になると思います。

スキャフォールディング機能
http://surferonwww.info/BlogEngine/post/2017/07/23/creating-controller-and-view-in-mvc-using-scaffolding-function.aspx

投稿2018/12/03 02:51

退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

blackdifferent

2018/12/03 06:07

回答いただきありがとうございます。 NorthWindのダウンロードがうまくいかず、参考のスキャホールディング機能は試せずにいます。 しかし制作中のものも同様にEntity Framework(Index)で作成したもので、それを一覧表示頁で編集できるようリストでデータの受け渡し、保存にしたものです。 回答でいただいたプログラムでは、Dropdownlistの初期値にDBの値がセットされるのでしょうか? ちなみにDBにはTKintaiとTSituationがあり、TSituationにIDとSituationがありリストに選択肢を入れます。リストの選択項目が他の情報とともにTKintaiに保存されます。
退会済みユーザー

退会済みユーザー

2018/12/03 06:17

> 回答でいただいたプログラムでは、Dropdownlistの初期値にDBの値がセットされるのでしょうか? そうです。アップしたコードの SelectList コンストラクターの第 4 引数で指定してます。
blackdifferent

2018/12/03 07:35

なるほど。 制作中のコードですとリストで渡しているため、SelectList内で選択項目を指定するのが出来なさそうです。 ビュー側で選択項目を指定する方法はありますでしょうか?
退会済みユーザー

退会済みユーザー

2018/12/03 08:40

> 制作中のコードですとリストで渡しているため、SelectList内で選択項目を指定するのが出来なさそうです。 意味が分かりません。SelectList を渡せるように変更すれば済む話だと思うのですが? > ビュー側で選択項目を指定する方法はありますでしょうか? 普通のやり方でやる方法は自分は知りません。項目は渡せるでしょうから、JavaScript でなんちゃらするということは可能かもしれません。でも、そこまでやるの? SelectList を渡すようにすべきじゃないの?・・・って思います。
退会済みユーザー

退会済みユーザー

2018/12/03 23:55

質問者さんのケース(複数行の一括更新・・・個人的にはかなり乱暴なような気もしますが)の場合に SelectList を ViewBag 経由で View に渡すにはどうするかを考えてみましたので、回答欄に追記しておきます。
退会済みユーザー

退会済みユーザー

2018/12/04 00:34

文字数制限があるのか、最初の回答欄には追記できなかったので、新たに別の回答欄を設けてそこに書きました。
guest

0

SurferOnWwwさんの回答にて解決しました。
最終的なコードをこちらに載せます。

コントローラ:

using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using Kintai_CS_.Models; namespace Kintai_CS_.Controllers { public class TKintaisController : Controller { private mvcdbEntities db = new mvcdbEntities(); // GET: TKintais public ActionResult Index() { //選択ボックスのオプションを準備 List<TSituation> situations = db.TSituation.ToList(); Dictionary<int, SelectList> dictionary = new Dictionary<int, SelectList>(); foreach (TSituation item in situations) { dictionary.Add(item.id, new SelectList(situations, "ID", "Situation", item.id)); } ViewBag.Situation = dictionary; return View(db.TKintai.ToList()); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Index(List<TKintai> products) { foreach(var kintai in products) { TKintai sv_product = db.TKintai.Find(kintai.id); sv_product.open = kintai.open; sv_product.close = kintai.close; sv_product.rest = kintai.rest; sv_product.situation = kintai.situation; sv_product.remark = kintai.remark; if (kintai.open != null && kintai.close != null && kintai.rest != null) { kintai.worktime = kintai.close - kintai.open - kintai.rest; kintai.overtime = kintai.worktime - TimeSpan.FromHours(8); } } db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }

ビュー:

@model IList<Kintai_CS_.Models.TKintai> @{ /**/ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; Dictionary<int, SelectList> dictionary = (Dictionary<int, SelectList>)ViewBag.Situation; } <h2>Index</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <table class="table"> <tr> <th> id </th> <th> week </th> <th> open </th> <th> close </th> <th> rest </th> <th> worktime </th> <th> overtime </th> <th> situation </th> <th> 補助 </th> <th> remark </th> </tr> @for (int i = 0; i < Model.Count; i++) { int idx = i; <tr> <td> @Html.DisplayFor(model => model[idx].id) @Html.HiddenFor(model => model[idx].id) </td> <td> @Html.DisplayFor(model => model[idx].week) @Html.HiddenFor(model => model[idx].week) </td> <td> @Html.EditorFor(model => model[idx].open, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model[idx].open, "", new { @class = "text-danger" }) </td> <td> @Html.EditorFor(model => model[idx].close, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model[idx].close, "", new { @class = "text-danger" }) </td> <td> @Html.EditorFor(model => model[idx].rest, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model[idx].rest, "", new { @class = "text-danger" }) </td> <td> @Html.DisplayFor(model => model[idx].worktime) @Html.HiddenFor(model => model[idx].worktime) </td> <td> @Html.DisplayFor(model => model[idx].overtime) @Html.HiddenFor(model => model[idx].overtime) </td> <td> @Html.DropDownListFor(model => model[idx].situation, dictionary[Model[idx].situation], new { htmlAttributes = new { @class = "form-control" } }) </td> <td style="width: 66px"> <nobr> <button type="button" onclick="location.href='@Url.Action("BtnClick","Kintai")'">定</button> </nobr> </td> <td> @Html.EditorFor(model => model[idx].remark, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model[idx].remark, "", new { @class = "text-danger" }) </td> </tr> } </table> <p> <input type="submit" value="更新" /> </p> }

投稿2018/12/06 04:53

blackdifferent

総合スコア25

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

ベストアンサー

【追伸】

最初の回答の 2018/12/04 08:55 の私のコメントで「質問者さんのケース(複数行の一括更新・・・個人的にはかなり乱暴なような気もしますが)で SelectList を ViewBag 経由で View に渡すにはどうするかを考えてみました・・・」と書きましたが、それを以下に書いておきます。

Dictionary<int, SelectList> 型のディクショナリを作り(key が situation に該当)、それを ViewBag 経由 View に渡し、ディクショナリの中から key が situation に該当する SelectList を取得して @Html.DropDownLsit の第 2 引数に渡してやります。

イメージ説明

編集後 POST したときにモデルバインディングが期待通り行われるように、 @Html.DropDownLsit の第 1 引数にも一工夫必要ですので注意してください。

上の画像のコードは以下の通りです。

Model

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace Mvc5App.Models { public class KintaiModel { public IList<TKintai> Kintais { get; set; } } public class TKintai { public int Id { set; get; } public string Week { set; get; } public string Open { set; get; } public string Close { set; get; } public string Rest { set; get; } public string Worktime { set; get; } public string Overtime { set; get; } public int Situation { set; get; } public string Remark { set; get; } } public class TSituation { public int ID { set; get; } public string Situation { set; get; } } }

Controller / Action Method

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.ComponentModel.DataAnnotations; using Mvc5App.Models; namespace Mvc5App.Controllers { public class HomeController : Controller { public ActionResult EditKintai() { KintaiModel model = new KintaiModel(); model.Kintais = new List<TKintai> { new TKintai { Id = 1, Week = "w1", Open = "o1", Close = "c1", Rest = "rs1", Worktime = "w1", Overtime = "o1" , Situation = 1, Remark = "rm1" }, new TKintai { Id = 2, Week = "w2", Open = "o2", Close = "c2", Rest = "rs2", Worktime = "w2", Overtime = "o2" , Situation = 2, Remark = "rm2" }, new TKintai { Id = 3, Week = "w3", Open = "o3", Close = "c3", Rest = "rs3", Worktime = "w3", Overtime = "o3" , Situation = 3, Remark = "rm3" } }; List<TSituation> situations = new List<TSituation> { new TSituation { ID = 1, Situation = "状態1" }, new TSituation { ID = 2, Situation = "状態2" }, new TSituation { ID = 3, Situation = "状態3" } }; Dictionary<int, SelectList> dictionary = new Dictionary<int, SelectList> { { 1, new SelectList(situations, "ID", "Situation", 1) }, { 2, new SelectList(situations, "ID", "Situation", 2) }, { 3, new SelectList(situations, "ID", "Situation", 3) } }; ViewBag.Situation = dictionary; return View(model); } [HttpPost] public ActionResult EditKintai(KintaiModel model) { if(ModelState.IsValid) { // DB の編集処理 return RedirectToAction("Index"); } return View(model); } } }

View

@model Mvc5App.Models.KintaiModel @{ ViewBag.Title = "EditKintai"; Layout = "~/Views/Shared/_Layout.cshtml"; Dictionary<int, SelectList> dictionary = (Dictionary<int, SelectList>)ViewBag.Situation; } <h2>EditKintai</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>KintaiModel</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <fieldset> <legend>Fields</legend> <table> <tr> <th> id </th> <th> week </th> <th> open </th> <th> close </th> <th> rest </th> <th> worktime </th> <th> overtime </th> <th> situation </th> <th> remark </th> </tr> @for (int i = 0; i < Model.Kintais.Count; i++) { <tr> <td> <div class="editor-field"> @Html.TextBoxFor(model => model.Kintais[i].Id, new { style = "width:60px" }) @Html.ValidationMessageFor(model => model.Kintais[i].Id) </div> </td> <td> <div class="editor-field"> @Html.TextBoxFor(model => model.Kintais[i].Week, new { style = "width:60px" }) @Html.ValidationMessageFor(model => model.Kintais[i].Week) </div> </td> <td> <div class="editor-field"> @Html.TextBoxFor(model => model.Kintais[i].Open, new { style = "width:60px" }) @Html.ValidationMessageFor(model => model.Kintais[i].Open) </div> </td> <td> <div class="editor-field"> @Html.TextBoxFor(model => model.Kintais[i].Close, new { style = "width:60px" }) @Html.ValidationMessageFor(model => model.Kintais[i].Close) </div> </td> <td> <div class="editor-field"> @Html.TextBoxFor(model => model.Kintais[i].Rest, new { style = "width:60px" }) @Html.ValidationMessageFor(model => model.Kintais[i].Rest) </div> </td> <td> <div class="editor-field"> @Html.TextBoxFor(model => model.Kintais[i].Worktime, new { style = "width:60px" }) @Html.ValidationMessageFor(model => model.Kintais[i].Worktime) </div> </td> <td> <div class="editor-field"> @Html.TextBoxFor(model => model.Kintais[i].Overtime, new { style = "width:60px" }) @Html.ValidationMessageFor(model => model.Kintais[i].Overtime) </div> </td> <td> <div class="editor-field"> @*@Html.TextBoxFor(model => model.Kintais[i].Situation, new { style = "width:60px" })*@ @Html.DropDownList("Kintais[" + i + "].Situation", dictionary[Model.Kintais[i].Situation]) @Html.ValidationMessageFor(model => model.Kintais[i].Situation) </div> </td> <td> <div class="editor-field"> @Html.TextBoxFor(model => model.Kintais[i].Remark, new { style = "width:80px" }) @Html.ValidationMessageFor(model => model.Kintais[i].Remark) </div> </td> </tr> } </table> </fieldset> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Save" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }

【追伸】

下の 2018/12/06 12:12 の私のコメントで「こうしてみてはどうかという案を回答欄に追記しておきます」と書きましたが、それを以下に書いておきます。

コメントにも書きましたが、検証等はしておりませんので参考にとどめ、自力で必要な修正等を行ってコードを書いてください。

質問者さんの Controller のコードの中の、

// 選択ボックスのオプションを準備 ViewBag.ServerOptions = db.TSituation.Select(s => new SelectListItem { Text = s.situation, Value = s.id.ToString() });

を以下のように変更して、

List<TSituation> situations = db.TSituation.ToList(); Dictionary<int, SelectList> dictionary = new Dictionary<int, SelectList>(); foreach (TSituation item in situations) { dictionary.Add(item.ID, new SelectList(situations, "ID", "Situation", item.ID)); } ViewBag.Situation = dictionary;

View を以下のようにしたらどうなりますか?

@model List<Kintai_CS_.Models.TKintai> @{ /**/ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; Dictionary<int, SelectList> dictionary = (Dictionary<int, SelectList>)ViewBag.Situation; } ・・・略・・・ @Html.DropDownList("<name 属性に指定する名前>", dictionary[Model[idx].Situation]) ・・・略・・・

(注)上のコードの <name 属性に指定する名前> は EditorFor を使った際にどのようになるか調べて、同じになるように設定してください

投稿2018/12/04 00:32

編集2018/12/06 03:16
退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

blackdifferent

2018/12/04 02:07

詳細に回答いただきありがとうございます! すみません、もしよろしければTKintaiとTSituationをDB(SQL Server)とリンクさせるところを教えていただけますか?
退会済みユーザー

退会済みユーザー

2018/12/04 02:18

SQL Server の既存の DB に TKintai テーブルと TSituation テーブルがあって、それから List<T> 型のオブジェクトを取得したいのでしょうか? 既存の DB から DB First で ADO.NET Entity Data Model を作ったのですよね? であれば、私が書いた最初のサンプルの例で言うと、List<T> 型のオブジェクトは、以下のようにして取得できます。同じようにできるのでは? private NORTHWINDEntities db = new NORTHWINDEntities(); var list1 = db.Products.ToList(); var list2 = db.Suppliers.ToList();
blackdifferent

2018/12/05 02:56

すみません。いろいろ試してみましたが、うまくいきませんでした。 回答2のコードにDBのTKintaiとTSituationをリンクさせて、値を入れたり編集したり出来るようにしたいのですが、そのあたりを教えていただけないでしょうか?
退会済みユーザー

退会済みユーザー

2018/12/05 03:24

平易にかつ十二分に説明したつもりなので、これ以上何を答えればいいのか分かりません。「うまくいきません」と言われても何もわからないですし。 2 番目の回答にアップしたコードはそのままコピペすれば動くはずですが、試してもらえましたか? まだなら試してどういう動きになっているのか理解することをお勧めします。その上で、具体的に、私のサンプルに質問者さんの DB を当てはめるための課題は何か、課題を解決するために何を聞きたいのか書いていただければと思います。
blackdifferent

2018/12/05 04:14

2番目の回答のコードはうまく動きました。 それでmodel.KintaisにDBのTKintaiの値を引っ張ってこようと思ったのですが、それがうまくいきませんでした。
退会済みユーザー

退会済みユーザー

2018/12/05 04:57

「うまくいきません」では何もわからないと言っているのですが。 その引っ張ってくるというのを具体的にどのようにしたのか、どういうことを期待ししていたが、結果はどうなってしまったのかを書きましょう。 書く気がないなら自分は撤退します。
blackdifferent

2018/12/05 08:43

何度もすみません。 回答2のコントローラで、 KintaiModel model = new KintaiModel(); model.Kintais = db.TKintai.ToList(); としてdbのTKintaiテーブルの値を入れようとしましたが、エラーが出ます。 (エラー:'System.Collections.Generic.List<WebApplication1.Models.TKintai>' を 'System.Collections.Generic.IList<WebApplication1.Models.KINTAI>' に暗黙的に変換できません。明示的な変換が存在します (cast が不足していないかどうかを確認してください)) TSituationのデータをDropdownlistに入れることは出来ましたが、TKintaiが入りません。よろしくお願いします。
退会済みユーザー

退会済みユーザー

2018/12/05 09:50 編集

そもそも、ドロップダウンリストを使う前(質問のコードで EditorFor を DropDownListFor に変更する前)は、一覧の表示と編集後の POST でのモデルバインディングは期待通りできていたのですか? そうであれば、最初の質問にアップしてあった Controller のコードは、Dictionary<int, SelectList> 型のオブジェクトを作り ViewBag に代入するところ以外は、何も変更する必要はないと思います。 > TSituationのデータをDropdownlistに入れることは出来ましたが というところが具体的にどうなっているのか書いてないので分かりませんが、それが私がサンプルで書いたような Dictionary<int, SelectList> 型のオブジェクトとして渡せていれば、あとは View のコードの問題で、私がサンプルに書いたようにしてできると思うのですが? とにかく、あなたが何をしたのか詳しく書いてないので、ピンポイントでどこをどうすればいいかは第三者には指摘でないということを理解して、十分な情報を書くようお願いします。
blackdifferent

2018/12/06 01:24

そうですね。質問コードでEditorForの一覧表示と編集後のモデルバインディングは出来ていました。 Dropdownlistで選択肢表示は出来るものの、過去に保存した項目をDropdownlistの初期値として表示することが出来なかったため質問させていただきました。 もう少しDictionary型やViewBagについて勉強し、実装できないか確認したいと思います。
退会済みユーザー

退会済みユーザー

2018/12/06 03:12

こうしてみてはどうかという案を回答欄に追記しておきます。検証等はしておりませんので参考にとどめ、自力で必要な修正等を行ってコードを書いてください。
blackdifferent

2018/12/06 04:33

ありがとうございます。出来ました。 DropDownList()だとバインドがされなかったので、DropDownListFor()にしたところ全てうまく機能しました。 本当にありがとうございました。後で最終的なコードもアップしようと思います。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問