MVC 编辑帖子返回下拉列表的多个“选定”ID
本文关键字:选定 ID 编辑 返回 下拉列表 MVC | 更新日期: 2023-09-27 18:29:43
因此,在为模型中的外键字段选择新的 ID 值时,我遇到了问题。我使用ViewBag
(是的,我知道这是一种肮脏的方法(将SelectList
发送到页面。它看起来像:
[Authorize(Roles = "Administrator")]
public ActionResult Edit(int id = 0)
{
var carriers = db.GetMobileCarriers().Select(m => new { Id = m.Id, Name = m.Name }).ToDictionary(s => s.Id, s => s.Name);
var notify = db.NotificationMethods.Select(n => new { Id = n.Id, Name = n.Name }).ToDictionary(n => n.Id, n => n.Name);
ViewBag.Carriers = new SelectList(carriers, "Key", "Value");
ViewBag.NotifyMethods = new SelectList(notify, "Key", "Value");
Contact contact = db.Contacts.Find(id);
if (contact == null)
{
return HttpNotFound();
}
return View(contact);
}
在页面中,我使用以下方法来生成 HTML:
<div data-role="fieldcontain">
<div class="editor-label" style="vertical-align:top;">
@Html.LabelFor(model => model.PhoneCarrierId)
</div>
<div class="editor-field" style="width: 500px !important;">
@Html.DropDownListFor(model => model.PhoneCarrierId, (SelectList)ViewBag.Carriers)
@Html.ValidationMessageFor(model => model.PhoneCarrierId)
</div>
</div>
<div data-role="fieldcontain">
<div class="editor-label" style="vertical-align:top;">
@Html.LabelFor(model => model.NotificationMethodId)
</div>
<div class="editor-field" style="width: 500px !important;">
@Html.DropDownListFor(model => model.NotificationMethodId, (SelectList)ViewBag.NotifyMethods)
@Html.ValidationMessageFor(model => model.NotificationMethodId)
</div>
</div>
我在控制器中的 POST 方法如下所示:
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Administrator")]
public ActionResult Edit(Contact contact, FormCollection form)
{
if (ModelState.IsValid)
{
db.Entry(contact).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(contact);
}
我添加FormCollection
仅用于调试目的。问题是返回的所选NotificationMethodId
与选择新之前相同。它在 GET 上显示正确选择的 Id。奇怪的是,当我查看FormCollection
时,NotificationMethodId
的数据有两个键值。一个用于原始 ID,一个用于新选择的 ID。但是模型总是绑定到第一个模型,即原始的,未经编辑的模型。另一个奇怪的事情是,对于以完全相同方式设置和使用PhoneCarrierId
字段,它不会以这种方式运行。因此,我一定错过了什么。
FormCollection
包含 2 个NotificationMethodId
值的事实表明您在视图中有第二个输入 NotificationMethodId
,很可能是隐藏的输入,并且它位于 DropDownListFor()
方法之前(DefaultModelBinder
将仅绑定第一个值并忽略第二个同名值(
旁注:没有必要使用 ToDictionary()
.相反,你代码t生成选择列表可以简单地
var carriers = db.GetMobileCarriers();
ViewBag.Carriers = new SelectList(carriers, "Id", "Name");