You could do this by manually parsing the FormCollection
object, but it would make for tedious code. However this may be necessary if you can't control the names of the POSTed values.
public ActionResult Customer(FormCollection response)
{
for (int i = 0; i < response["CustomerCount"]; i++
{
list.Add(
new Customer
{
ID = response["Customer" + i + ".ID"],
Name = response["Customer" + i + ".Name"],
...
});
}
}
But a much cleaner way is using MVC's automatic binding, which works for lists as well:
The query string from user:
/Customer/Add?myList[0].ID=2&myList[0].Name=Bob&myList[1].ID=18&myList[1].Name=Alice
The controller:
public CustomerController : Controller
{
public ActionResult Add(List<Customer> myList)
{
var test = myList.Count; // 2
var test2 = myList[1].Name; // Alice
}
}
If possible, using the HtmlHelper
methods in your Razor view to create those inputs, takes all the guesswork out of this. An example to edit current customers:
@model MyNamespace.ViewModels.CustomerEditViewModel
@Html.BeginForm("Edit", "Customer")
{
@* Show all current customers for editing *@
@for (int i=0; i < Model.Customers.Count; i++)
{
@Html.TextBoxFor(x => x.Customers[i].ID)
@Html.TextBoxFor(x => x.Customers[i].Name)
}
<input type="submit" />
}
Note: Customers is a List<Customer>
in the CustomerEditViewModel
class passed with return View(myViewModel);