title: How to bind complex properties within polymorphic model in Asp.Net MVC 4?
body: <p>I need to create a dynamic input form based on a derived type but I cannot get complex properties bound properly when passed to the POST method of my controller.  Other properties bind fine.  Here is a contrived example of what I have:</p>
  
  <p><strong>Model</strong></p>
  
  <pre><code>public abstract class ModelBase {}
  
  public class ModelDerivedA : ModelBase
  {       
      public string SomeProperty { get; set; }       
      public SomeType MySomeType{ get; set; }
  
      public ModelDerivedA()
      {
          MySomeType = new SomeType();
      }
  }
  
  public class SomeType 
  {             
      public string SomeTypeStringA { get; set; }
      public string SomeTypeStringB { get; set; }         
  }
  </code></pre>
  
  <p><strong>Custom Model Binder</strong></p>
  
  <p>The binder is based on this answer: <a href="https://stackoverflow.com/questions/7222533/polymorphic-model-binding">polymorphic-model-binding</a></p>
  
  <pre><code>public class BaseViewModelBinder : DefaultModelBinder
  {
      protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
      {
          var typeValue = bindingContext.ValueProvider.GetValue("ModelType");
          var type = Type.GetType(
              (string)typeValue.ConvertTo(typeof(string)),
              true
          );
          if (!typeof(ModelBase).IsAssignableFrom(type))
          {
              throw new InvalidOperationException("The model does not inherit from mode base");
          }
          var model = Activator.CreateInstance(type);
          bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() =&gt; model, type);
          return model;
      }
  }
  </code></pre>
  
  <p><strong>Controller</strong></p>
  
  <pre><code>[HttpPost]
  public ActionResult    GetDynamicForm([ModelBinder(typeof(BaseViewModelBinder))] ModelBase model)
  {
     // model HAS values for SomeProperty 
     // model has NO values for MySomeType
  }
  </code></pre>
  
  <p><strong>View Excerpt</strong></p>
  
  <pre><code>@Html.Hidden("ModelType", Model.GetType())
  @Html.Test(Model);
  </code></pre>
  
  <p><strong>JavaScript</strong></p>
  
  <p>The form is posted using <code>$.ajax</code> using <code>data: $(this).serialize()</code>, which, if I debug shows the correct populated form data.</p>
  
  <p>All properties are populated in the model excluding those of <code>SomeType</code>.  What do I need to change to get them populated?</p>
  
  <p>Thanks</p>