Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 628
Faizan S. Avatar asked Jan 28 '10 15:01

Faizan S.


People also ask

What is the use of FormCollection?

Form collection is used to retrieve input elements from the controller action method. Form collection class automatically receives the data form value in controller methods in the form of key/value pair. Key and value pairs are accessed using the key name and index value.

What is FormCollection in ASP NET MVC?

FormCollection is one way of retrieving view data in controller. Depending on the type of value in input, you can parse its non-string value to string in the Action method.

What is form collection?

The Form collection is used to retrieve the values of form elements from a form that uses the POST method.


1 Answers

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.

like image 181
Mattias Jakobsson Avatar answered Oct 23 '22 11:10

Mattias Jakobsson