I have a table with different rows, and each row corresponds to an ID. For each line, I have the EDIT option, which when selected should allow the user to view the default values โโcorresponding to this identifier in the Edit.chtml "fields, and then update it, deleting the default values โโand enter a new record and save it.
In ' Edit.chtml , I have a field for "MANAGERS" which I need to populate with a drop-down list of names with the default value / selected value corresponding to the identifier of the row where the Edit operation is selected from the table. I use viewBag, but my problem is that the drop-down list always displays the first item in the list, not the selected value. Please see the code below.
Controller: // // GET: /ManagersNAMES/Edit/5 public ActionResult Edit(int id) { using (var db = new InpEntities()) { var list_managers = (from x in db.TABLE_MANAGERS select new TABLE_MANAGERSDTO { ID = x.ID, NAME = x.NAME, }).OrderBy(w => w.NAME).ToList(); ViewBag.managers = new SelectList(list_managers, "ID", "NAME", id); return View(); } } public class TABLE_MANAGERSDTO { public string NAME { get; set; } public int ID { get; set; } } // // POST: /ManagersNAMES/Edit/5 [HttpPost] public ActionResult Edit(int id, TABLE_INSTITUTES dp) { try { using (var db = new InpEntities()) { TABLE_INSTITUTES tmp = (TABLE_INSTITUTES)db.TABLE_INSTITUTES.Where(f => f.ID == id).First(); tmp.MANAGER = dp.MANAGER; db.SaveChanges(); return RedirectToAction("Index"); } } catch { return View(); } }
View: Edit.chtml
@{ ViewBag.Title = "Edit"; } <h2>Edit</h2> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <div class="editor-label" style="font-weight:bold">MANAGER</div> <div class="editor-field"> @Html.DropDownList("dp.MANAGER", (SelectList)ViewBag.managers) </div> <p> <input type="submit" value="Save" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div>
source share