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.
I would recommend you the following article which illustrates a nice helper that you could use for achieving that instead of using magic strings.