这是来自 Contoso 大学在线示例的代码:
控制器:
[HttpGet]
public ActionResult Edit(int id)
{
Department department = departmentService.GetById(id);
PopulateAdministratorDropDownList(department.PersonID);
return View(department);
}
// POST: /Department/Edit/5
[HttpPost]
public ActionResult Edit(Department department)
{
try
{
if (ModelState.IsValid)
{
departmentService.Update(department);
return RedirectToAction("Index");
}
}
catch (DataException)
{
//Log the error (add a variable name after DataException)
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem
persists, see your system administrator.");
}
PopulateAdministratorDropDownList(department.PersonID);
return View(department);
}
private void PopulateAdministratorDropDownList(object selectedAdministrator = null)
{
var administrators = instructorService.GetAll().OrderBy(i => i.LastName);
ViewBag.PersonID = new SelectList(administrators, "PersonID", "FullName",
selectedAdministrator);
}
看法:
<div class="editor-field">
@Html.DropDownList("PersonID", String.Empty)
@Html.ValidationMessageFor(model => model.PersonID)
</div>
我的问题是:如果在视图中我们没有访问 ViewBag.PersonID(我们只是创建一个 DropDownList,它会生成一个带有 ID="PersonID" 的 html 选择列表,没有任何默认选择值),那么 ViewBag 到底是怎么回事。 PersonID 属性绑定到那个 DropDownList?幕后发生了什么?这看起来像魔术!
第二个问题是在发布数据时,我认为控制器在视图中搜索其 ID 与模型中的属性匹配的任何 html 表单字段,这就是我们在回发时获取所选 Department.PersonID 的方式,即使视图代码不不要引用模型(类似于模型 => model.PersonID)对吗?