在我看来,我有:
<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的值是正确的值,并且该值确实存在于下拉列表中,但由于某种原因它未被选中。我怎样才能做到这一点?
答案 0 :(得分:0)
更改
ID = t.ID,
new SelectList(technicians, "ID", "Name", techID);
要
Id = t.ID,
new SelectList(technicians, "Id", "Name", techID);
我的预感是你在Id
模型中定义User
。它应该有Id
和Name
。
修改
如果techID
是整数,请确保传入匿名对象:
new SelectList(technicians, "Id", "Name", new { Id = techID });