我正在尝试为控制器中的下拉菜单设置所选值,并通过ViewBag将其传递给我的视图。当我调试时,所有正确的值也被传递给控制器和视图,但是当它实际在页面上呈现时,没有设置所选的值。
查看
<tr class="form-group">
<th>
<label for="CompanyID" class="control-label col-md-9">Company</label>
</th>
<td>
@Html.DropDownList("CompanyID", (IEnumerable<SelectListItem>)ViewBag.CompanyID, "", new { @class = "required-validation" })
@Html.ValidationMessageFor(model => model.CompanyID)
</td>
控制器
public ActionResult Edit(int? id) {
if (id == null) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var sale = db.SalesOpportunities.Find(id);
if (sale == null) {
return HttpNotFound();
}
ViewBag.CompanyID = new SelectList(db.Companies, "CompanyID", "Name", sale.CompanyID);
var technicians = db.UserProfiles.Select(t => new {
ID = t.ID,
Name = t.FirstName + " " + t.LastName,
}).OrderBy(t => t.Name);
ViewBag.UserID = new SelectList(technicians, "ID", "Name", sale.UserID);
return View(sale);
}
答案 0 :(得分:4)
您选择的字段名称和ViewBag
中变量的名称不能相同。将其从ViewBag.CompanyID
更改为类似ViewBag.CompanyChoices
的内容,它会起作用。