title: How to delete rows dynamically with jquery from an asp.net view model without deleting the rest of the next objects in the collection
body: <p>From what I understand, I have an indexation problem. Let's start with the actual code (this is a fragment from the whole page code, but other fragments, which are similar to this, also fail to work):</p>
  
  <p>The cshtml code that creates Generic Object partial views.</p>
  
  <pre><code>&lt;div id="genericObjects"&gt;
  @if (Model.GenericObjects != null &amp;&amp; Model.GenericObjects.Any())
  {
    for (int i = 0; i &lt; Model.GenericObjects.Count; i++)
    {
        { Html.RenderPartial("_GenericObject", Model, new ViewDataDictionary(this.ViewData) { { "GenericIndex", i } }); }
    }
  }
  &lt;/div&gt;
  </code></pre>
  
  <p>The _GenericObject partial view:</p>
  
  <pre><code>model Noodle.Presentation.Models.MashupViewModel
  
  @{
     var f = Html.Bootstrap().Misc().GetBuilderFor(new Form().Type(FormType.Horizontal).LabelWidthMd(3));
      var index = (int)ViewBag.GenericIndex;
  }
  
  &lt;div class="row generic"&gt;
    &lt;h4&gt;
      &lt;span&gt;Object&lt;/span&gt;
      @Html.Bootstrap().Button().Class("remove-generic pull-right").PrependIcon("glyphicon glyphicon-trash").Text("")
    &lt;/h4&gt;
    @f.FormGroup().TextBoxFor(s =&gt; Model.GenericObjects[index].Name).Label().ShowRequiredStar(false)
    @f.FormGroup().TextBoxFor(s =&gt; Model.GenericObjects[index].ForeignId).Label().ShowRequiredStar(false)
    @f.FormGroup().TextBoxFor(s =&gt; Model.GenericObjects[index].Value).Label().ShowRequiredStar(false)
  
  &lt;/div&gt;
  </code></pre>
  
  <p>The GetGenericObject method for invoking the partial view:</p>
  
  <pre><code>public PartialViewResult GetGenericObject(int? index)
          {
              ViewBag.GenericIndex = index;
              return PartialView("_GenericObject");
          }
  </code></pre>
  
  <p>Here are the addition (works fine) and deletion jquery methods:</p>
  
  <pre><code>$('#mashup-form').on('click', '.add-generic-object-btn', function () {
                  var index = $('#genericObjects').children().length;
                  $('&lt;div&gt;').load(genericObjPath + '?index=' + index, function () {
                      $('#genericObjects').append($(this).find('.generic')[0].outerHTML);
                      revalidate();
                  });
              });
  </code></pre>
  
  <p>AND</p>
  
  <pre><code>$('#mashup-form').on('click', '.remove-generic', function () {
                  $(this).parent().parent().remove();
  });
  </code></pre>
  
  <p>As for the actual problem, let's say we have three generic objects:</p>
  
  <p>TEST1
  TEST2
  TEST3</p>
  
  <p>If TEST2 is deleted, the generic objects that come after it are not submitted (although they do appear on the page).</p>
  
  <p>Essentially, what remains on page:</p>
  
  <p>TEST1,
  TEST3</p>
  
  <p>What is submitted in the model:</p>
  
  <p>TEST1</p>
  
  <p>The rest of the code works just fine. There is no real point in showing the c# method call on submit, as it works perfectly, but receives a model, that does not have the TEST3 object in it. </p>
  
  <p>Now, this seems to be an indexation problem, which I tried to fix by altering the code like this (the idea was taken from another StackOverflow thread [<a href="https://stackoverflow.com/questions/25993763/delete-table-row-dynamically-using-jquery-in-asp-net-mvc]">delete table row dynamically using jQuery in asp.net mvc</a>):</p>
  
  <pre><code> $('#mashup-form').on('click', '.remove-generic', function () {
     $(this).parent().parent().remove();
     var index = 0;
     var itemIndex = 0;
     $('#genericObjects').each(function () {
       var this_row = $(this);
       this_row.find('input[name$=".Name"]').attr('name', 'Model.GenericObjects[' + itemIndex + '].Name');
       this_row.find('input[name$=".ForeignId"]').attr('name', 'Model.GenericObjects[' + itemIndex + '].ForeignId');
       this_row.find('input[name$=".Value"]').attr('name', 'Model.GenericObjects[' + itemIndex + '].Value');
       itemIndex++;
     });
   });
  </code></pre>
  
  <p>The result was rather bizarre. Again, if we have three Objects TEST1 TEST2 TEST3, by deleting TEST1 and submitting, I got only TEST2 and by only I mean the entire model was wiped, but this object (the model has more objects, this is just a fragment of the page). Also, if TEST2 is deleted, TEST1 is the only object in the view model (everything else is null). If the delete button on the generic objects is not pressed, everything works just fine.</p>
  
  <p>So, if you have any ideas on how to fix this, please tell them. Also, if there is some other info or code you might need, feel free to ask. Admittedly, I might not be able to give it, but I will see what can be done. Have a good one!</p>
  
  <p>AFTER SOLVING ISSUE EDIT:</p>
  
  <p>I marked the answer below, which involves using EditorFor, as the accepted answer, because I find it is well written and could be useful to somebody, who reads this question and cannot make the partial views work at all. However, in my case, I could make the previous system work. I made a very basic stupid mistake, by only specifying the element outside the partial view. So this:  </p>
  
  <pre><code>$('#mashup-form').on('click', '.remove-generic', function () {
     $(this).parent().parent().remove();
     var index = 0;
     var itemIndex = 0;
     $('#genericObjects').each(function () {
       var this_row = $(this);
       this_row.find('input[name$=".Name"]').attr('name', 'Model.GenericObjects[' + itemIndex + '].Name');
       this_row.find('input[name$=".ForeignId"]').attr('name', 'Model.GenericObjects[' + itemIndex + '].ForeignId');
       this_row.find('input[name$=".Value"]').attr('name', 'Model.GenericObjects[' + itemIndex + '].Value');
       itemIndex++;
     });
   });
  </code></pre>
  
  <p>Essentially became this:</p>
  
  <pre><code>$('#mashup-form').on('click', '.remove-generic', function () {
     $(this).parent().parent().remove();
     var index = 0;
     var itemIndex = 0;
     $('#genericObjects div.row.generic div.col-md-12').each(function () {
       var this_row = $(this);
       this_row.find('input[name$=".Name"]').attr('name', 'GenericObjects[' + itemIndex + '].Name');
       this_row.find('input[name$=".ForeignId"]').attr('name', 'GenericObjects[' + itemIndex + '].ForeignId');
       this_row.find('input[name$=".Value"]').attr('name', 'GenericObjects[' + itemIndex + '].Value');
       itemIndex++;
     });
   });
  </code></pre>
  
  <p>As for the nested objects, the indexation approach is very similar to the one in the accepted answer (in EditorFor system), but they have names. So, instead of [0].<a href="https://i.stack.imgur.com/PPyxN.png" rel="nofollow noreferrer">1</a>.TESTAs[3], you would have TESTCs[0].TESTBs<a href="https://i.stack.imgur.com/PPyxN.png" rel="nofollow noreferrer">1</a>.TESTAs[3] (this is for an object class TESTC, which containts TESTB class objects, which in turn contain TESTA class objects).</p>
  
  <p>Sadly, I probably can't show the code I made for resetting the indexes (I think it was a rather nice reusable method), but I can outline the core concept. First of all, as long as .each refers to every HTML element created on the necessary, you only have to specify the root of the elements and just use .find, to find every input by their name and change the necessary index in them (you don't have to navigate to them, since you will want to reset all of them anyway).</p>
  
  <p>As for the resetting, I was already using jquery, so I just used the .attr .replace method. The replacing was done via a regex, which I can hopefully somewhat share.</p>
  
  <p>For the first hierarchical level, use this:</p>
  
  <pre><code>(.*?\[)(.*?)\] 
  </code></pre>
  
  <p>and the string to replace by should be "$1" + index + "]"</p>
  
  <p><a href="https://i.stack.imgur.com/PPyxN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PPyxN.png" alt="enter image description here"></a></p>
  
  <p>Level 2 is simply copy paste of the first one:</p>
  
  <pre><code>(.*?\[)(.*?\[)(.*?)\], where (.*?\[) is a single instance of symbols till [
  </code></pre>
  
  <p>and the string to replace by should be "$1$2" + index + "]"</p>
  
  <p><a href="https://i.stack.imgur.com/V7ynH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V7ynH.png" alt="enter image description here"></a></p>
  
  <p>Further levels are achieved by just copying the (.*?[) whatever amount of times needed and adding accordingly "$1$2$3... group identifiers in the replacement string. This also seems pretty universal (doesn't matter what the object names actually are). You will of course need to specify all the input field names though. Have a good one. Hope this maybe helps someone somehow.</p>
  
  <p>AFTER EDIT 2: I noticed in the comment by Stephen Muecke a rather nice way of dealing with the problem as well. In this particular situation I didn't use it though, as I want to avoid modifying the core system as much as possible. However, I would advise you to have a look at this solution, since this ultimately can make you avoid doing any index resetting whatsoever.</p>