title: Dynamically add new fields with Editor Template
body: <p>In my MVC4 project I have a Category view model with a collection of Product view models. I use an Editor Template to render a single Product view model, and pass the collection of Product view models to it:</p>
  
  <p>Category view model:</p>
  
  <pre><code>@model CategoryViewModel
  @using MVC4PartialViews.Models.ViewModels
  
  &lt;div class="editor-field"&gt;
      @Html.EditorFor(model =&gt; model.CategoryName)
      @Html.ValidationMessageFor(model =&gt; model.CategoryName)
  &lt;/div&gt;
  
  @Html.EditorFor(x =&gt; x.Products)
  </code></pre>
  
  <p>Editor template that renders each Product in the collection:</p>
  
  <pre><code>&lt;div class="editor-field"&gt;
      @Html.EditorFor(model =&gt; model.ProductName)
      @Html.ValidationMessageFor(model =&gt; model.ProductName)
  &lt;/div&gt;
  // etc.
  </code></pre>
  
  <p>This works very well as it automagically names and indexes the elements correctly so all the Products get posted back as part of the parent Category view model - here's what it outputs:</p>
  
  <pre><code>&lt;div class="editor-field"&gt;
      &lt;input class="text-box single-line" id="Products_0__ProductName" name="Products[0].ProductName" type="text" value="Add 1st product for this Category" /&gt;
      &lt;span class="field-validation-valid" data-valmsg-for="Products[0].ProductName" data-valmsg-replace="true"&gt;&lt;/span&gt; 
  &lt;/div&gt;
  </code></pre>
  
  <p>I need to lets users add and remove Products. To add a new one I somehow need to dynamically render the editor template to create the new Product and have each field indexed / named correctly i.e if I already have 2 Products (indexed 0 and 1) then the new Product would need to be named as such: </p>
  
  <pre><code>Products[2].ProductName
  </code></pre>
  
  <p>I've read this article by Steve Sanderson but it seems clunky and he indexes his fields with a Guid rather than a consecutive index field:</p>
  
  <p><a href="http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/" rel="nofollow">Editing a variable length list in MVC2</a></p>
  
  <p>TIA</p>