Proper way of using FormCollection in ASP.NET MVC2 Create Method?

Faizan S. picture Faizan S. · Jan 28, 2010 · Viewed 11.3k times · Source

I am currently developing an application with the new ASP.NET MVC2 framework. Originally I started writing this application in the ASP.NET MVC1 and I'm basically just updating it to MVC2.

My problem here is, that I don't really get the concept of the FormCollection object vs. the old Typed object.

This is my current code:

[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");
    }
}

This is the Code from the MVC1 application:

[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));
}

What are the benefits of switching to FormCollection in MVC2 and more importantly - how is it used properly?

Answer

Mattias Jakobsson picture Mattias Jakobsson · Jan 28, 2010

You had the FormCollection object in v1 as well. But it is more preferred to use a typed object. So if you are already doing that, then continue doing so.