I have a form on a razor view page where I am adding rows dynamically using jQuery. I want to bind the dynamically created fields to an array so that I can browse through the array one at a time and insert them to a table in the database. The problem is the fields appear in the "FormCollection" as individual fields rather than as an array.
Please see the attached image for view page:
jQuery script to add new rows:
$(function() {
var tableRowNum = 1;
$("#add-work-row").click(function () {
tableRowNum++;
var tableRow = "<tr>";
tableRow += "<td><input name='works[" + (tableRowNum - 1) + "].workCover' type='checkbox' class='text' /></td>";
tableRow += "<td><input name='works[" + (tableRowNum - 1) + "].workTitle' type='text' class='text work-title caps' /></td>";
tableRow += "<td><input name='works[" + (tableRowNum - 1) + "].workComposers' type='text' class='text work-composer caps' /></td>";
tableRow += "<td><input name='works[" + (tableRowNum - 1) + "].workPerformances' type='text' class='text work-performances' /></td>";
tableRow += "<td><input name='works[" + (tableRowNum - 1) + "].workDuration' type='text' class='text work-duration input-duration' /></td>";
tableRow += "<td><a href='#' class='delete-row'></a></td>";
tableRow += "</tr>";
$("#worksTable").append(tableRow);
return false;
});
});
The controller action is:
public ActionResult CreateReport(FormCollection form)
{
// works is null?
var works = form["works"];
foreach (var work in works)
{
// Do something
}
return null;
}
FormCollectionIn MVC you bind to your model. And you have not even shown how your generating the new rows or the model you need to bind to.FormCollectionuseIEnumerable<YourViewModel>, where theYourViewModelrepresents a row in a table. See Phil Haack's artile on model binding: haacked.com/archive/2008/10/23/model-binding-to-a-list.aspxWorkswhich is a collection of a model that contains properties namedWorkCover,WorkTitleetc. but there are other problems with your code and it will never work if you deleted an item.