title: ASP.Net Core Razor Pages dynamic list
body: <p>I want to create a website with Razor pages to maintain spaces and the according rooms.
  So, in my model a space has a list of rooms.</p>
  
  <pre><code>public class Space
  {
      public int Id { get; set; }
      public string SpaceName { get; set; }
      public List&lt;Room&gt; Rooms { get; set; }
  
      public Space()
      {
          this.Rooms = new List&lt;Room&gt;();
      }
  }
  </code></pre>
  
  <p>In the create.cshtml I want to dynamically add and remove rooms </p>
  
  <pre><code>&lt;h1&gt;Create New Space&lt;/h1&gt;
  &lt;form method="post"&gt;
      &lt;div class="form-group"&gt;
         &lt;label for="Space.SpaceName"&gt;Space Name&lt;/label&gt;
         &lt;input type="text" class="form-control" asp-for="Space.SpaceName" placeholder="Enter space name"&gt;
         &lt;span asp-validation-for="Space.SpaceName" &gt;&lt;/span&gt;
      &lt;/div&gt;
      @if(Model.Space != null){
          for (int i = 0; i &lt; Model.Space.Rooms.Count; i++)
          {
           &lt;input asp-for="@i" type="hidden" /&gt;
           &lt;div class="form-group"&gt;
               &lt;label for="SpaceName"&gt;Room Name&lt;/label&gt;
               &lt;input type="text" class="form-control" asp-for="Space.Rooms[i].Name" placeholder="Enter space name"&gt;
               &lt;span asp-validation-for="Space.Rooms[i].Name" &gt;&lt;/span&gt;
           &lt;/div&gt;
  
           &lt;button type="submit" asp-page-handler="removeroom" asp-route-index="@i"&gt;Remove Room&lt;/button&gt;
           }
      }
  
      &lt;button type="submit" asp-page-handler="addroom"&gt;Add Room&lt;/button&gt;
  
      &lt;button type="submit" asp-page-handler="submit" class="btn btn-primary"&gt;Submit&lt;/button&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>The PageModel looks like this:</p>
  
  <pre><code>public class CreateModel : PageModel
  {
      readonly SpaceRepository spaceRepository;
  
      public CreateModel(SpaceRepository spaceRepository)
      {
          this.spaceRepository = spaceRepository;
      }
  
      [BindProperty]
      public Space Space { get; set; }
  
      public async Task&lt;IActionResult&gt; OnPostSubmitAsync()
      {
          if (!ModelState.IsValid)
          {
              return Page();
          }
  
          spaceRepository.Create(Space);
          return RedirectToPage("./Index");
      }
  
      public async Task OnPostAddRoomAsync()
      {
          Space.Rooms.Add(new Room());
      }
  
      public async Task OnPostRemoveRoomAsync(int index)
      {
          Space.Rooms.RemoveAt(index);
      }
  }
  </code></pre>
  
  <p>So far it works as expected, but when I create for example 3 rooms and delete the first or second one, it always deletes the last one. </p>
  
  <p>The page seems not to receive the manipulated list after the handler post.</p>
  
  <p>Any ideas what's missing?</p>
  
  <p>Thank you for your help!</p>