代码之家  ›  专栏  ›  技术社区  ›  Faizan S.

在ASP.NET MVC2创建方法中使用FormCollection的正确方法?

  •  8
  • Faizan S.  · 技术社区  · 15 年前

    我目前正在使用新的ASP.NET MVC2框架开发应用程序。最初我开始在ASP.NET MVC1中编写这个应用程序,我只是将其更新为MVC2。

    我这里的问题是,我不太了解FormCollection对象和旧类型化对象的概念。

    这是我当前的代码:

    [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有什么好处?更重要的是,它是如何正确使用的?

    2 回复  |  直到 13 年前
        1
  •  11
  •   Mattias Jakobsson    15 年前

    在v1中也有FormCollection对象。但更倾向于使用类型化对象。如果你已经这样做了,那么继续这样做。

        2
  •  0
  •   user74754    13 年前

    通过使用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。