这是Contoso大学在线示例代码:ViewBag
控制器:
[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?幕后发生了什么?这看起来像魔术!
第二个问题是发布数据时,我认为控制器在视图中搜索任何与表单中的模型属性相匹配的html表单字段,这就是我们如何在回发中获取选定的Department.PersonID,即使视图代码不会引用模型(像model => model.PersonID),对吗?