如何重新计算表单数组
我希望用户一次更新多行,所以我创建了一个这样的表单(我删除了 HTML 以显示我的真正意思):
@using(Html.BeginForm()) {
@{int i = 0; }
@foreach(var row in Model) {
@Html.TextBox("Customer["+ i +"].CustomerID")
@Html.TextBox("Customer["+ i +"].Name")
}
<input type="submit" />
}
HTML 中的输出是(3 行):
<input type="text" name="Customer[0].CustomerID" />
<input type="text" name="Customer[0].Name" />
<input type="text" name="Customer[1].CustomerID" />
<input type="text" name="Customer[1].Name" />
<input type="text" name="Customer[2].CustomerID" />
<input type="text" name="Customer[2].Name" />
当用户单击提交按钮时,数据被发送到控制器:
Public ActionResult EditCustomer(IEnumerable<Customer> Customer) {
}
这给了我一个很好的 IEnumerable ,其中包含所有输入的数据,我可以做任何我想做的事情。它按预期工作。
现在我想更进一步并允许用户删除行。
这失败了
因为当我删除第二行时,数组不再“关闭”:它从 Customer[0] 到 Customer[2] 并且 ASP.NET MVC 存在问题。
所以我认为可以通过重新计算索引来解决这个问题。但我该如何在 jQuery 中做到这一点呢?
因此,删除中间行后,会运行一个函数,将 Customer[2].CustomerID
更新为 Customer[1].CustomerID
。
I want the user to update multiple rows at once so I created a form like this (I stripped out the HTML to show what I really mean):
@using(Html.BeginForm()) {
@{int i = 0; }
@foreach(var row in Model) {
@Html.TextBox("Customer["+ i +"].CustomerID")
@Html.TextBox("Customer["+ i +"].Name")
}
<input type="submit" />
}
The output in HTML is (for 3 rows):
<input type="text" name="Customer[0].CustomerID" />
<input type="text" name="Customer[0].Name" />
<input type="text" name="Customer[1].CustomerID" />
<input type="text" name="Customer[1].Name" />
<input type="text" name="Customer[2].CustomerID" />
<input type="text" name="Customer[2].Name" />
When the user clicks the submit button, the data is sent to a Controller:
Public ActionResult EditCustomer(IEnumerable<Customer> Customer) {
}
Which gives me a nice IEnumerable with all the entered data and I can do whatever I want. It works as expected.
Now I'd like to take it one step further and allow the user to remove rows.
This fails
Because when I remove the second row, the array is no longer 'closed': it goes from Customer[0] to Customer[2] and ASP.NET MVC has problems with that.
So I think that can be solved with recalculating the indexes. But how do I do this in jQuery?
So that after the middle row has been deleted a function is run that updates Customer[2].CustomerID
to Customer[1].CustomerID
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会推荐您 下面的文章说明了一个很好的助手,您可以使用它来实现这一目标,而不是使用魔术字符串。
I would recommend you the following article which illustrates a nice helper that you could use for achieving that instead of using magic strings.