gpt4 book ai didi

c# - Html.dropdownlist 不显示下拉字段中的默认/选定值

转载 作者:太空狗 更新时间:2023-10-29 21:45:14 26 4
gpt4 key购买 nike

我有一个包含多行的表格,每行对应一个 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并输入新条目并保存。

在“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();
}
}

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>

最佳答案

您需要像这样在 Controller 中设置选定的 id:

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);

并将您的 View 更改为:

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

关于c# - Html.dropdownlist 不显示下拉字段中的默认/选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17026616/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com