title: ASP.NET MVC ViewModel with IEnumerable Property
body: <p><strong>What I am Attempting</strong></p>
  
  <p>I am trying to bind my ViewModel to my View which contains a Customer Name and a list of Contacts to reach that customer. Once the view is populated I also want the user to have the ability to add, delete, and edit contacts in the View.</p>
  
  <p><strong>What I've got so far</strong></p>
  
  <p>Currently I am able to bind to the ViewModel using the EditorTemplate and edit the data with no problems. The problem comes in when I want to add or remove rows in the list, if a user deletes row 5 from the middle of the ViewModel bound Editable List only rows 1 - 4 will end up being posted to the server.</p>
  
  <p><strong>The Code</strong></p>
  
  <p>Here is what my ViewModel looks like:</p>
  
  <pre><code>    public class CustomerViewModel{
         [Required]
         public int CustomerUniqueID { get; set; }
         [Required]
         public string Name { get; set; }
  
         public IEnumerable&lt;CustomerContacts&gt; Contacts { get; set; }
  
         public CustomerViewModel() { }
         public CustomerViewModel(Customer customer)
         {
          ICustomerContactRepository contacts = new LockShop.Domain.Concrete.EFCustomerContactRepository();
          this.Contacts = contacts.FindContacts(customer.UniqueID);
  
          this.Name = customer.Name;
      }
  }
  </code></pre>
  
  <p>I am passing my ViewModel to my view like this:</p>
  
  <pre><code>        public ActionResult Edit(){
             Customer customer = repository.Customers.FirstOrDefault(c =&gt; c.UniqueID == 23128);
             return View(new CustomerViewModel(customer));            
          }
  </code></pre>
  
  <p>When it is time to render the list, I simply use the EditorFor helper:</p>
  
  <pre><code>@Html.EditorFor(model =&gt; model.Contacts)
  </code></pre>
  
  <p>What I love about this approach is that when I click the save button all of my changes are automatically posted to the controller! </p>
  
  <p><strong>My Question</strong></p>
  
  <p>What are the best practices of how to add the functionality of adding and removing rows to a list that is generated by an IEnumerable from my ViewModel?</p>
  
  <p><strong>What I Have Tried</strong></p>
  
  <p>I've read Steven Sanderson's blog post which talks about <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</a> in ASP.NET MVC. His post seems to only cover binding to a model and doesn't cover the possibility of binding to a list in a ViewModel. When I implemented his solution the post data from the Contacts list that got sent back to the controller was null.</p>
  
  <p>Please feel free to ask any questions for clarification and thanks for your time.</p>