I have a table where I add and remove rows dynamically:
@model AHBReports.Models.AdjustmentModel
@using (Html.BeginForm())
{
<table id="container">
@Html.EditorFor(model => model.Adjustments)
</table>
<div >
<input type="button" id="btnAdd" value="+ Add" />
<input type="submit" value="Submit" />
</div>
}
EditorTemplate:
@model AHBReports.Models.Adjustment
<tr>
<td>@Html.HiddenFor(x => x.Id, new { @class = "iHidden" })</td>
<td>@Html.AutocompleteFor(model => model.BRANCH, "GetBranches", "Report700H")</td>
<td>@Html.EditorFor(model => model.Amount)</td>
<td><a onclick="removeRow(this)">x</a></td>
</tr>
Script for table manipulation:
<script type="text/javascript">
function removeRow(selector)
{
if ($('#container tr').length > 1)
{
$(selector).closest('tr').remove();
}
}
$(document).ready(function () {
$("#btnAdd").click(function (e) {
var ind = $("#container tr:last").find("input.iHidden").val();
var itemIndex = parseInt(ind);
itemIndex++;
console.log(itemIndex);
e.preventDefault();
var newItem = $("<tr>"+
"<td><input id='Adjustments_" + itemIndex + "__Id' type='hidden' value='"+itemIndex+"' class='iHidden' name='Adjustments[" + itemIndex + "].Id' /></td>" +
"<td><input type='text' id='Adjustments_" + itemIndex + "__BRANCH' name='Adjustments[" + itemIndex + "].BRANCH' data-autocomplete-url='@Url.Action("GetBranches", "Report700H")'/></td>" +
"<td><input type='text' id='Adjustments_" + itemIndex + "__Amount' name='Adjustments[" + itemIndex + "].Amount'/></td>" +
"<td><a onclick='removeRow(this)'>x</a></td>" +
"</tr>");
$("#container").append(newItem);
});
});
My add/delete functions work fine visually in my view, as well as when I accept the collection in my POST method:
public ActionResult Adjust(AdjustmentModel model)
{
//working with model.Adjustments
}
I receive correct values. However, when I try to delete some row, which is in the middle of the table and then sumbit the form, I receive only elements that were above deleted row, for example:
id branch amount
0 aaa 500
1 bbb 200
2 ccc 300 --deleted this row
3 ddd 400
Collection receives:
id branch amount
0 aaa 500
1 bbb 200
So, the last row is missing. What am I doing wrong??
Thanks a lot