I\'m developing an ASP.NET MVC 5 web with C# and .NET Framework 4.5.1.
I have this form
in a cshtml
file:
@model MyProduct.
You need to generate the controls for the collection in a for
loop so they are correctly named with indexers (note that property BatchProducts
needs to be IList
@using (Html.BeginForm("Save", "ConnectBatchProduct", FormMethod.Post))
{
....
Then the POST method needs to be
public ActionResult Save(ConnectBatchProductViewModel model)
{
....
}
Edit
Note: Further to your edit, if you want to dynamically add and remove BatchProductViewModel
items in he view, you will need to use the BeginCollectionItem
helper or a html template as discussed in this answer
The template to dynamically add new items would be
Note the dummy indexers and the non-matching value for the hidden input prevents this template posting back.
Then the script to add a new BatchProducts
would be
$("#addrow").click(function() {
var index = (new Date()).getTime(); // unique indexer
var clone = $('#NewBatchProduct').clone(); // clone the BatchProducts item
// Update the index of the clone
clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
clone.html($(clone).html().replace(/"%"/g, '"' + index + '"'));
$("table.order-list").append(clone.html());
});