ViewBag SelectList未设置所选值

时间:2014-10-01 15:44:58

标签: c# asp.net-mvc

在我看来,我有:

<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的值是正确的值,并且该值确实存在于下拉列表中,但由于某种原因它未被选中。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

更改

ID = t.ID,
new SelectList(technicians, "ID", "Name", techID);

Id = t.ID,
new SelectList(technicians, "Id", "Name", techID);

我的预感是你在Id模型中定义User。它应该有IdName

修改

如果techID是整数,请确保传入匿名对象:

new SelectList(technicians, "Id", "Name", new { Id = techID });
相关问题