title: Serializing Form Data Collection to Model using JavaScript
body: <p>Let's say I have an object like this:</p>
  
  <pre><code>public class Widget
  {
      public string Name { get; set; }
      public IEnumerable&lt;Foo&gt; Foos { get; set; }
  }
  
  public class Foo
  {
      public string Name { get; set; }
  }
  </code></pre>
  
  <p>And my controller method sends it to a View like this:</p>
  
  <pre><code>var widget = _dataAccess.GetWidget(someKey);
  return View(widget);
  </code></pre>
  
  <p>And I have a View that looks like this:</p>
  
  <pre><code>@model MyNamespace.Widget
  
  @using(Html.BeginForm("Edit", "Widgets", FormMethod.Post, new { id = "the-form" }))
  {
      &lt;p&gt;@Html.TextBoxFor&lt;/p&gt;
  
      @foreach(var foo in Model.Foos)
      {
          &lt;p&gt;@Html.TextBoxFor(x =&gt; x.Foos.ToList()[Model.Foos.ToList().IndexOf(foo)])&lt;/p&gt;   
      }
  
      &lt;input type="button" value="Save Changes" id="the-button" /&gt;
  }
  
  &lt;script type="text/javascript"&gt;
  $(function () {
          $("#the-button").click(function () {
              $.ajax({
                  url: '@Url.Action("Edit", "Widgets")',
                  type: 'POST',
                  data: JSON.stringify({ widget: serializeForm("the-form") }),
  
                  // etc, etc, not important
              });
          });
      });
      function serializeForm(formId) {
          var formData = {};
          $.each($("#" + formId).serializeArray(), function(){
              formData[this.name] = $(this).val();
          });
          return formData;
      }
  &lt;/script&gt;
  </code></pre>
  
  <p>Which serializes into:</p>
  
  <pre><code>{ "widget": { "Name" : "value from textbox", "[0].Name" : "some value", "[1].Name" : "some other value" } }
  </code></pre>
  
  <p>Of Course the serialization here isn't helpful because <code>[0].Name</code> isn't usable. Is there a way to change this so that it serializes to what the Post method controller action would expect? I.e., something like:</p>
  
  <pre><code>{ "widget":{"Name":"blah", "Foos":[ { "Name":"foo name 1"}, { "Name":"foo name 2"} ] }}
  </code></pre>