2013-03-07 32 views
3

這是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),對嗎?

回答

1

幕後:

視圖呼籲Html.DropdownList(this HtmlHelper htmlHelper, string name, string optionLabel)最終結束調用SelectExtensions.SelectInternal(htmlHelper, metadata, optionLabel, expression, selectList, allowMultiple, htmlAttributes1)這將檢查selectList1爲空,如果如果是,它調用SelectExtensions.GetSelectData(htmlHelper, name)這不檢查一個視圖數據的魔法的一部分關鍵匹配你傳遞的名稱

發帖:

你這裏的假設是非常正確的,但除了形成領域的框架也將檢查查詢字符串和路由數據和任何其他IValueProvi這是插入管道。