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;
}