Christopher Johnson
Christopher Johnson

Reputation: 2629

passing form data to controller mvc3

I'm brand new to .net MVC3 so pardon my ignorance. I have a relatively large form (lots of fields) and I'm just wondering if I really need to reference each one of my fields as arguments to my action method on the back end or if it's possible to pass them all in as some sort of collection then reference the collection to obtain the values.

If that's possible could someone please provide a short example of how?

thanks

Upvotes: 3

Views: 6193

Answers (2)

Craig Stuntz
Craig Stuntz

Reputation: 126547

Shortest example I can come up with...

View model:

public class ViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

View:

<%: Html.EditorForModel() %>

Controller

[HttpGet]
public ActionResult Person()
{
     return View(new ViewModel());
}
[HttpPost]
public ActionResult Person(ViewModel formData)
{
     // formData is bound already -- just use it!
}

Upvotes: 4

Jamie Dixon
Jamie Dixon

Reputation: 53991

You can pass all the data to the controller as a custom type.

public ActionResult MyControllerMethod(MyCustomType formData)

If you strongly type your view then you'll be able to render the form fields using the HtmlHelper such as:

<%= Html.TextBoxFor(m => m.FirstName) %>

This was the ID of the form fields, which is used to associate the form field with the model property, will already be set for you.

Upvotes: 0

Related Questions