这是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?幕后发生了什么?这看起来像魔术!!!
第二个问题是在发布数据时,我认为控制器在视图中搜索任何html表单字段,其ID与模型中的属性匹配,这就是我们如何在回发上获取所选的Department.PersonID,即使视图代码不引用模型(像model =&gt; model.PersonID那样somtheing)对吗?
答案 0 :(得分:1)
在幕后:
视图正在调用Html.DropdownList(this HtmlHelper htmlHelper, string name, string optionLabel)
,最终调用SelectExtensions.SelectInternal(htmlHelper, metadata, optionLabel, expression, selectList, allowMultiple, htmlAttributes1)
这会将selectList1
检查为null,如果是,则调用SelectExtensions.GetSelectData(htmlHelper, name)
执行魔术部分检查查看数据以查找与您传入的名称相匹配的密钥。
张贴:
您的假设非常正确,但除了表单字段外,框架还将检查查询字符串和路由数据以及插入管道的任何其他IValueProvider。