Asp.net

在 ASP.NET MVC2 創建方法中使用 FormCollection 的正確方法?

  • February 28, 2012

我目前正在使用新的 ASP.NET MVC2 框架開發應用程序。最初我開始在 ASP.NET MVC1 中編寫這個應用程序,我基本上只是將它更新到 MVC2。

我的問題是,我並沒有真正理解 FormCollection 對象與舊的 Typed 對象的概念。

這是我目前的程式碼:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
   try
   {
       Member member = new Member();
       member.FirstName = collection["FirstName"];
       member.LastName = collection["LastName"];
       member.Address = collection["Address"];

       // ...

       return RedirectToAction("Details", new { id = member.id });
   }
   catch
   {
       return View("Error");
   }
}

這是來自 MVC1 應用程序的程式碼:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Member member)
{
   try
   {
       memberRepository.Add(member);
       memberRepository.Save();

       return RedirectToAction("Details", new { id = member.id });
   }
   catch
   {
   }
   return View(new MemberFormViewModel(member, memberRepository));
}

在 MVC2 中切換到 FormCollection 有什麼好處,更重要的是 - 它是如何正確使用的?

您在 v1 中也有 FormCollection 對象。但更優選使用類型化對象。因此,如果您已經這樣做了,請繼續這樣做。

通過使用 FormCollection,您最終可以手動匹配您的文章數據或查詢字元串鍵/值到值以使用字元串類型(導致字元串類型的程式碼)在您的程式碼中使用,而內置的模型綁定可以為您執行此操作如果您使用表單模型,也就是“類型化對象”。

我認為通過使用 FormCollection,您可能還會失去在模型對像上使用方便的數據註釋(斜線驗證)屬性的能力,這些屬性設計用於類型化對像模型綁定。

此外,一旦你開始接觸你的 controller.Request.Form,單元測試就會變得更加麻煩。您可能會發現自己必須模擬和設置一個 HttpContextBase 和一個 HttpRequestBase,只是為了讓該模擬請求的 .Form 屬性返回您希望測試看到的 NameValueCollection。將此與讓模型綁定為您完成工作進行對比,例如:

 // Arrange
 var myModel = new MyModel( Property1 = "value1", Property2 = "value2");
 // Act
 var myResult = myController.MyActionMethod(myModel);
 // Assert
 // whatever you want the outcome to be

總而言之,我建議不要盡可能地使用 FormCollection。

引用自:https://stackoverflow.com/questions/2155857