我有一个包含不同行的表,每一行对应一个 ID。For every row, I have EDIT option which when selected should enable the user to look at the default values corresponding to that ID in the ' Edit.chtml ' fields and there by update it by erasing the default values and typing in the new entry and保存它。
在“ Edit.chtml ”中,我有一个“MANAGERS”字段,我需要使用名称下拉列表填充该字段,其中显示的默认/选定值对应于从表中选择编辑操作的行的ID。我正在使用 viewBag 但我的问题是下拉列表始终显示列表中的第一项而不是选定的值。 请看下面的代码。
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();
}
}
查看:' 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>