I am using a form with a for loop, depending on the amount the form input fields will be created. I want to return a list of Formcollection. I know that formcollection only returns one form but I want to return many forms(list) So my controller method only works with 1 form My Controller:
[HttpPost]
public ActionResult SecondStepProcessValid(FormCollection form)
{
List<Customer> itemList = new List<Customer>();
int i = 0;
itemList.Add(new Customer()
{
Name = form["Name"],
Emailaddress = form["Email"],
HouseNumber = Int32.Parse(form["HouseNumber"]),
Zipcode = form["Zipcode"]
});
foreach (var c in itemList)
{
customerRepository.Create(c);
}
return View("ThirdStepProcess");
}
my view
<form method="post" action="@Url.Action("SecondStepProcessValid")">
@for (int i = 0; i < Model.Amount; i++)
{
<div class="space">
<div><br /></div>
<div>Guest@(@i + 1)</div>
</div>
<div class="space">
<div>Name</div>
<div>@Html.TextBox("Name", Model.NewCustomers[i].Name)</div>
</div>
<div class="space">
<div>Email</div>
<div>@Html.TextBox("Email", Model.NewCustomers[i].Emailaddress)</div>
</div>
<div class="space">
<div>House Number</div>
<div>@Html.TextBox("HouseNumber", Model.NewCustomers[i].HouseNumber)</div>
</div>
<div class="space">
<div>Zipcode</div>
<div>@Html.TextBox("Zipcode", Model.NewCustomers[i].Zipcode)</div>
</div>
<input type="hidden" name="Index" value="@i" />
}
<input type="submit" value="Step 3" />
</form>
You cannot have multiple forms posted together. But you can post multiple items in a form or multiple
List<T>as well.For that, you need to make your view strongly typed and then in action you can have a parameter of type
List<Customer>or a container view model with a property of typeList<Customer>which would look like:Change your view to be strongly typed with that model and render the input control using the strongly typed helpers to avoid silly typo mistakes that can happen using magic string and take benefit from model and visual studio intellisence and compile time safety from errors :
now in controller you can have a parameter to which you view strongly typed:
Hope it gives idea.