Html.dropdownlist does not display default value / selected in dropdown list box

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> 
+6
source share
2 answers

You need to set the selected identifier in the controller as follows:

 var list_managers = list_managers.Select(x => new { Value = x.ID.ToString(), Text = x.Name }) .ToList(); ViewBag.managers = new SelectList(list_managers, "ID", "NAME", id); 

And change your mind to:

 @Html.DropDownList("dpMANAGER", (SelectList)ViewBag.managers) 
+2
source

Just wrote @Html.DropDownList("dp.MANAGER", ViewBag.managers) without selectlist, because it is already in the SelectList type.

And write ViewBag.managers = new SelectList(list_managers, "ID", "NAME"); in the following way

+2
source

Source: https://habr.com/ru/post/946968/


All Articles