ViewBag SelectList未设置所选值
本文关键字:设置 SelectList ViewBag | 更新日期: 2023-09-27 18:25:24
在我看来,我有:
<tr class="form-group">
<th><label class="control-label">Technician</label></th>
<td>
@Html.DropDownListFor(model => model.UserID, (IEnumerable<SelectListItem>)ViewBag.TechnicianID)
@Html.ValidationMessageFor(model => model.UserID)
</td>
</tr>
在我的控制器中:
public ActionResult Edit(int? id) {
var salescall = (id != null) ? db.SalesCalls.Find(id) : new SalesCall();
if (salescall == null) {
return HttpNotFound();
}
ViewBag.CompanyID = new SelectList(db.Companies, "CompanyID", "Name", salescall.CompanyID);
var technicians = db.UserProfiles.Select(t => new {
ID = t.ID,
Name = t.FirstName + " " + t.LastName,
}).OrderBy(t => t.Name);
var techID = CurrentUser.UserID(User);
ViewBag.TechnicianID = new SelectList(technicians, "ID", "Name", techID);
return View(salescall);
}
当我调试时,传递给techID的值是正确的值,该值确实存在于下拉列表中,但由于某种原因,它没有被选中。我怎样才能做到这一点?
更改
ID = t.ID,
new SelectList(technicians, "ID", "Name", techID);
至
Id = t.ID,
new SelectList(technicians, "Id", "Name", techID);
我的直觉是你在User
模型中定义Id
。它应该有Id
和Name
。
编辑
如果techID
是一个整数,请确保传入一个匿名对象:
new SelectList(technicians, "Id", "Name", new { Id = techID });