How to retrieve all values for all the inputs on MVC page

I have an MVC 3 project, that I am starting, using c# and Razor. I have a page, that has about 20 input fields that will be used. I create my ViewModel to pass the data to the View to create the page. I am confused as to, how I get the values of the fields, when the user submits the form.

Does my Controller have to have a parameter for every input field on my page? Is there any way to have the Controller get all the data on the page and then I can parse through it? The parameter list would be huge.

Answers


You can just use the same model that you passed to your view as the parameter in your subsequent action.

An example:

//This is your initial HTTP GET request.
public ActionResult SomeAction() {
    MyViewModel model;

    model = new MyViewModel();
    //Populate the good stuff here.

    return View(model);
}

//Here is your HTTP POST request; notice both actions use the same model.
[HttpPost]
public ActionResult SomeAction(MyViewModel model) {
    //Do something with the data in the model object.
}

The model object in the second method will automatically be populated from the data included in the HTTP request (the technical name is "Model Binding").


In your controller's action, expect to receive the same "model" you passed back to the view. This will works if you generated your 'input controls' properly (by using Html.TextBoxFor() or by setting the Name attribute to the same name of your model's properties).

public ActionResult MyAction(MyViewModel model) 
{ 
... 
} 

Note MVC will use a ModelBinder to figure out how to create and fill the properties of the object your action is expected based on the fields submitted from the user.

If you want to capture all inputs from the user you can make your action to receive an object of type FormCollection:

public ActionResult MyAction(FormCollection values) 
{ 
... 
} 

Please create an mvc action in your controller taking the model as parameter

Like this:

[HttpPost] or [HttpGet]
public ActionResult Employee(EmployeeModel employee)
{
// now you will have all the input inside you model properties
//Model binding is doen autoamtically for you
}

Need Your Help

Can I use Unit Testing tools for Integration Testing?

visual-studio-2010 unit-testing testing integration-testing

I'm preparing to create my first Unit Test, or at least that's how I was thinking of it. After reading up on unit testing this weekend I suspect I'm actually wanting to do Integration Testing. I ...

X axis with ggplot2 not sequential

r plot ggplot2 time-series dplyr

I have a small data set that I reproduced below. It has customers in rows and quantities per month in columns. I was using ggplot2 to plot it two weeks ago and it worked fine. But now, the time