Problem:
In an ASP.NET MVC application, an HTML form containing a dynamic array of input elements needs to be submitted as an IEnumerable
Solution:
Instead of using a FormCollection, the action method must accept an instance of the correct model type, ConnectBatchProductViewModel, as its parameter. To generate a form that posts form values to an IEnumerable property in the model, follow these steps:
Example Code:
Form Code:
@for(int i = 0; i < Model.BatchProducts.Count; i++) { <tr> <td>@Html.TextBoxFor(m => m.BatchProducts[i].Quantity)</td> <td>@Html.TextBoxFor(m => m.BatchProducts[i].BatchName)</td> <td> <input type="hidden" name="BatchProducts.Index" value="@i" /> <a class="deleteRow"></a> </td> </tr> }
Action Method:
public ActionResult Save(ConnectBatchProductViewModel model) { // Model binding will populate the BatchProducts property with data from the form. .... }
Dynamically Adding and Removing Items:
To enable dynamic adding and removing of items, use the BeginCollectionItem helper or an HTML template. The template for dynamically adding new items would be:
<div>
And the script to add a new BatchProducts item 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()); });
The above is the detailed content of How to Properly POST Form Arrays from ASP.NET MVC to an IEnumerable Model?. For more information, please follow other related articles on the PHP Chinese website!