在asp.net mvc中使用jQuery动态删除表行

我有一个表,我动态添加和删除行:

@model AHBReports.Models.AdjustmentModel @using (Html.BeginForm()) {  @Html.EditorFor(model => model.Adjustments) 
}

EditorTemplate:

 @model AHBReports.Models.Adjustment  @Html.HiddenFor(x => x.Id, new { @class = "iHidden" }) @Html.AutocompleteFor(model => model.BRANCH, "GetBranches", "Report700H") @Html.EditorFor(model => model.Amount) x  

表操作脚本:

  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 = $(""+ "" + "" + "" + "x" + ""); $("#container").append(newItem); }); }); 

我的添加/删除function在我的视图中以及在我的POST方法中接受集合时可视地工作:

  public ActionResult Adjust(AdjustmentModel model) { //working with model.Adjustments } 

我收到正确的价值观。 但是,当我尝试删除某些行(位于表格中间然后对表单进行求和)时,我只收到上面已删除行的元素,例如:

 id branch amount 0 aaa 500 1 bbb 200 2 ccc 300 --deleted this row 3 ddd 400 

收集收到:

 id branch amount 0 aaa 500 1 bbb 200 

所以,最后一行丢失了。 我究竟做错了什么??

非常感谢

当你删除它的行包含模型的输入和输入时,其名称和id基于索引。

因此,当您删除行时,您必须更新已删除行之后的行中的输入名称和ID。或者使用新索引名称从已删除行重新生成所有行。

用这个替换你的删除function

 function removeRow(selector) { if ($('#container tr').length > 1) { $(selector).closest('tr').remove(); var itemIndex =0; $('#container tr').each(function(){ var this_row = $(this); this_row.find('input[name$=".BRANCH"]').attr('name','Adjustments[' + itemIndex + '].BRANCH');//replace name of input that ends the name BRANCH this_row.find('input[name$=".Amount"]').attr('name','Adjustments[' + itemIndex + '].Amount'); this_row.find('input[name$=".Id"]').attr('name', 'Adjustments[' + itemIndex + '].Id'); itemIndex ++; }); } } 

集合的索引器必须从零开始并且是连续的,除非您使用Index属性,其中Index的值等于索引器。 例如

   

不会正确回发。 但是,如果为对象添加Index属性

       

然后该集合将正确回发

由于您无法访问EditorTemplate的索引器,因此您需要在主页面的for loop中生成控件

 for (int i = 0; i < Model.Adjustments.Count; i++) { var name = string.Format("Adjustments[{0}].Index", i); @Html.HiddenFor(m => m[i].ID) ....  } 

您还需要修改脚本以包含Index属性的隐藏输入。 而不是将itemIndex的值基于现有行的数量,而是基于唯一值。 例如

 $("#btnAdd").click(function (e) { var itemIndex = (new Date()).getTime(); 

你可以给该行一个唯一的ID。

 var newItem = $(""+ "" + "" + "" + "x" + "'); 

实际上这适用于我创建的一个熟悉的页面。

问候