title: Bind model with array property to form in ASP.NET Core MVC
body: <p>I'm trying to figure out how to bind form elements to model containing a property that is an array or enumerable. This form should be usable for adding a new object or editing an existing one.</p>
  
  <p>Below is a stripped down example.</p>
  
  <p>If Levels contains no elements (e.g. create), the row of Level fields is not rendered. Should you add an empty element to the Level array or should you add a row of empty fields? But how to do this using the asp-for attribute.</p>
  
  <p>If Levels contains elements (e.g. edit), the rows of Level fields is rendered. However, when posting <code>model.Levels</code> in the <code>Edit</code> method is <code>null</code>.</p>
  
  <p>Any ideas how to best implement this?</p>
  
  <p>Model to bind</p>
  
  <pre><code>public class CarparkModel
  {
    [HiddenInput]
    public int Id { get; set; }
    public string Name { get; set; }
    public Level[] Levels { get; set; }
  }
  
  public class Level
  {
     [HiddenInput]
     public int Id { get; set; }
     public string Description { get; set; }
     public int NrOfSpaces { get; set; }
  }
  </code></pre>
  
  <p>Main view</p>
  
  <pre><code>@model CarparkModel
  
  &lt;form method="POST"&gt;
    &lt;input asp-for="Id"&gt;
    &lt;div&gt;
      &lt;label asp-for="Name"&gt;&lt;/label&gt;
      &lt;input asp-for="Name"&gt;
    &lt;/div&gt;
    &lt;table&gt;
      &lt;tr&gt;
        &lt;th&gt;Description&lt;/th&gt;
        &lt;th&gt;Nr of spaces&lt;/th&gt;
      &lt;/tr&gt;
    @foreach (Level level in Model.Levels)
    {
      &lt;tr&gt;
        &lt;td&gt;&lt;input asp-for="Description"&gt;&lt;/td&gt;
        &lt;td&gt;&lt;input asp-for="NrOfSpaces"&gt;&lt;/td&gt;
      &lt;/tr&gt;
    }
      &lt;tr&gt;
        &lt;td colspan="2&gt;
          &lt;!-- Click = new row of Level fields added --&gt;
          &lt;button type="button"&gt;Add level&lt;/button&gt;
        &lt;/td&gt;
      &lt;/tr&gt;
    &lt;/table&gt;
    &lt;button type="submit"&gt;Save&lt;/button&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>Controller</p>
  
  <pre><code>public class CarparkController
  {
    [HttpGet]
    public IActionResult Create()
    {
      return View(new CarparkModel());
    }
  
    [HttpPost]
    public IActionResult Create(CarparkModel model)
    {
      if (ModelState.IsValid)
      {
        _repository.Save(model);
        return RedirectToAction("index");
      }
  
      return View(model);    
    }
  
    [HttpGet]
    public IActionResult Edit(int id)
    {
      return View(_repository.Get(id));
    }
  
    [HttpPost]
    public IActionResult Edit(CarparkModel model)
    {
      if (ModelState.IsValid)
      {
        _repository.Save(model);
        return RedirectToAction("index");
      }
  
      return View(model);    
    }
  }
  </code></pre>