我有一个表,我可以在其中动态添加和删除行:
@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>
}
编辑器模板:
@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 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);
});
});
我的添加/删除功能在我的 View 中以及在我的 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 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 ++;
});
}
}
关于c# - 在 asp.net mvc 中使用 jQuery 动态删除表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25993763/