2010-12-21 128 views
6

在Scott Hanselman的書(第1章)中,他爲我們提供了兩個選項來實現[HttpPost]創建操作方法。[HttpPost] public ActionResult創建(FormCollection集合)VERSUS [HttpPost] public ActionResult創建(晚餐晚餐)

第一個依靠TryUpdateModel根據傳入表單字段更新模型對象。當傳入表單域包含無效輸入時,ModelState.IsValid將被設置爲false。

 [HttpPost] 
     public ActionResult Create(FormCollection collection) 
     { 
      Dinner dinner = new Dinner(); 

      if (TryUpdateModel(dinner)) 
      { 
       dinnerRepository.Add(dinner); 

       dinnerRepository.Save(); 

       return RedirectToAction("Details", new { id = dinner.DinnerId }); 
      } 
      else 
       return View(dinner); 

     } 

第二種方法是利用作爲創建操作方法ARG如下傳遞模型:建議

 [HttpPost] 
     public ActionResult Create(Dinner dinner) 
     { 
      if (ModelState.IsValid) 
      { 
       dinnerRepository.Add(dinner); 

       dinnerRepository.Save(); 

       return RedirectToAction("Details", new { id = dinner.DinnerId }); 
      } 
      else 
       return View(dinner); 
     } 

哪一個更在生產中使用?

回答

5

如果您的所有數據都在Request.Form,路由數據或URL查詢字符串中,那麼您可以像在第二個示例中一樣使用模型綁定。

模型聯編程序創建您的晚餐對象,並通過匹配屬性名稱來填充請求中的數據。

您可以使用「白名單」,「黑名單」,前綴和標記界面來自定義綁定過程。 只要確保您不會無意中綁定值 - 請參閱此link

+0

感謝您回答並告知鏈接。 – xport 2010-12-21 07:56:07

相關問題