title: How to add an item to a list in a ViewModel using Razor and .NET Core?
body: <p>So here's my situation.</p>
  <p>Let's say I have a view called <code>TheView.cshtml.</code> <code>TheView.cshtml</code> has a ViewModel called <code>TheViewModel.cs</code>. In <code>TheViewModel.cs</code>, resides a List of an object (<code>TheObject</code>) called <code>TheObjectList</code>.</p>
  <p>I have an editor template for <code>TheObject</code> called <code>TheObject.cshtml</code>. Using this editor template, I can simply display all of the items in the <code>TheObjectList</code> with <code>@Html.EditorFor(model =&gt; model.TheObjectList)</code>.</p>
  <p>However, now I want to add objects to this list dynamically. I have an AJAX function, which calls a simple partial view to give the user a blank row to add a new &quot;<code>TheObject</code>&quot;, however, any new <code>TheObject</code> I add dynamically is not considered part of the original <code>TheObjectList</code>.</p>
  <p>This is because each item in the original <code>TheObjectList</code> is created with a certain prefix based on its index in the original list, whereas each new dynamic TheObject is created without a prefix, thus Razor does not see it as part of the list.</p>
  <p>Is there a way around this?</p>
  <p><strong>TheView.cshtml</strong></p>
  <pre><code>@model Models.ViewModels.TheViewModel
  
  &lt;table id=&quot;Table&quot;&gt;
      &lt;tbody&gt;
          @Html.EditorFor(m =&gt; m.TheObjectList);
      &lt;/tbody&gt;
  &lt;/table&gt;
  
  &lt;button id=&quot;AddObject&quot; type=&quot;button&quot; class=&quot;btn btn-primary&quot;&gt;Add Object&lt;/button&gt;
  </code></pre>
  <p><strong>TheViewModel.cs</strong></p>
  <pre><code>public class TheViewModel
  {
      public List&lt;TheObject&gt; TheObjectList { get; set; }
  }
  </code></pre>
  <p><strong>AddObject Controller Method</strong></p>
  <pre><code>public IActionResult AddObject()
  {
     return PartialView(&quot;_EmptyRow&quot;, new TheObject());
  }
  </code></pre>
  <p><strong>AJAX Method to Add Object</strong></p>
  <pre><code>$('#AddObject').click(function () {
      $.ajax({
          url: 'AddObject',
          cache: false,
          success: function (data) {
              $('#Table &gt; tbody').append(data);
          },
          error: function (a, b, c) {
              alert(a + &quot; &quot; + b + &quot; &quot; + c);
          }
       });
  });
  </code></pre>