我有一个表格,可以动态添加和删除行:
所以,最后一行缺失了。我做错了什么吗?非常感谢。
@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);
});
});
我的添加/删除功能在视图上看起来很好,当我在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
Collection接收:
id branch amount
0 aaa 500
1 bbb 200
所以,最后一行缺失了。我做错了什么吗?非常感谢。
form
。实际上,因为有@using (Html.BeginForm())
等内容,而不是渲染的HTML(这很重要,应该显示出来)... - Regent<form>
将之前的代码包装起来,它仍然可以工作:更新后的fiddle。 - Regent