title: MVC Model Binding a Complex Type to a Simple Type and Vice Versa
body: <p>Here's a scenario:</p>
  
  <p>I have an autocomplete plugin (custom) that keeps a hidden field of JSON objects (using a specific struct).</p>
  
  <p>I've created an Html helper that helps me easily bind to a specific custom model (basically, it has a JSON property that is for two-way binding and a property that lets me deserialize the JSON into the appropriate struct):</p>
  
  <pre><code>public class AutoCompleteModel {
      public string JSON { get; set; }
      public IEnumerable&lt;Person&gt; People {
          get {
              return new JavaScriptSerializer().Deserialize&lt;Person&gt;(this.JSON);
          }
          set {
              this.JSON = new JavaScriptSerializer().Serialize(value);
          }
       }
   }
  </code></pre>
  
  <p>This works great and I can model bind using the default binder <code>@Html.Autocomplete(viewModel =&gt; viewModel.AutoCompleteModelTest)</code>. The HTML helper generates HTML like:</p>
  
  <pre><code>&lt;input type="text" id="AutoCompleteModelTest_ac" name="AutoCompleteModelTest_ac" value="" /&gt;
  &lt;input type="hidden" id="AutoCompleteModelTest_JSON" name="AutoCompleteModelTest.JSON" value="{JSON}" /&gt;
  </code></pre>
  
  <p>The problem is this is not the best way for consumers. They have to manually set the People property to an array of Person structs. In my data layer, my domain objects probably will not be storing the full struct, only the person's ID (a corporate ID). The autocomplete will take care of looking up the person itself if only given an ID.</p>
  
  <p>The best scenario will be to call it like this:</p>
  
  <p><code>@Html.Autocomplete(domainObject =&gt; domainObject.PersonID)</code> or
  <code>@Html.Autocomplete(domainObject =&gt; domainObject.ListOfPersonIDs</code></p>
  
  <p>I would like it to work against the string property AND against the custom AutoCompleteModel. The autocompleter only updates a single hidden field, and that field name is passed back on postback (the value looks like: <code>[{ "Id":"12345", "FullName":"A Name"},{ "Id":"12347", "FullName":"Another Name" }]</code>).</p>
  
  <p>The problem is, of course, that those domain object properties only have an ID or array of IDs, not a full Person struct (so cannot be directly serialized into JSON). In the HTML helper, I can transform those property values into a struct, but I don't know how to transform it back into a simple type on POST. The solution I need would transform an ID into a new Person struct on page load, serializing it into the hidden field. On POST, it would deserialize the generated JSON back into a simple array of IDs.</p>
  
  <p>Is a custom model binder the solution I need? How can I tell it to work both with a custom model AND simple types (because I don't want it applied to EVERY string property, just need it to deal with the values given by the HTML helper).</p>