title: JSON custom binder null for derived abstract class asp.net mvc
body: <p>I have made a custom binder for an abstract class. The binder decides which implementation to use.
  It works well, but when I add a property which does not exist in the abstract class to a child class, it is always null.</p>
  
  <p>Here is the code for the abstract class <code>Pet</code> and derived classes <code>Dog</code> and <code>Cat</code>. </p>
  
  <pre><code>public abstract class Pet
  {
      public string name { get; set; }
      public string species { get; set; }
      abstract public string talk { get; }
  }
  
  public class Dog : Pet
  {
      override public string talk { get { return "Bark!"; } }
  }
  public class Cat : Pet
  {
      override public string talk { get { return "Miaow."; } }
      public string parasite { get;set; } 
  }
  
  
  public class DefaultPetBinder : DefaultModelBinder
  {
      protected override object CreateModel(ControllerContext controllerContext,ModelBindingContext bindingContext,Type modelType)
      {
          bool hasPrefix = bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName);
          string prefix = ((hasPrefix)&amp;&amp;(bindingContext.ModelName!="")) ? bindingContext.ModelName + "." : "";
  
          // get the parameter species
          ValueProviderResult result;
          result = bindingContext.ValueProvider.GetValue(prefix+"species");
  
          if (result.AttemptedValue.Equals("cat")){
              //var model = base.CreateModel(controllerContext, bindingContext, typeof(Cat));
              return base.CreateModel(controllerContext,bindingContext,typeof(Cat));
          }
          else (result.AttemptedValue.Equals("dog"))
          {
              return base.CreateModel(controllerContext,bindingContext,typeof(Dog));
          }
      }
  }
  </code></pre>
  
  <p>The controller just takes a <code>Pet</code> parameter and returns it as JSON. </p>
  
  <p>If I send</p>
  
  <pre><code>{name:"Odie", species:"dog"}
  </code></pre>
  
  <p>I get back</p>
  
  <pre><code>{"talk":"Bark!","name":"Odie","species":"dog"}
  </code></pre>
  
  <p>For the <code>Cat</code>, there is a parasite property which does not exist in the abstract class <code>Pet</code>. If I send</p>
  
  <pre><code>{"parasite":"cockroaches","name":"Oggy","species":"cat"}
  </code></pre>
  
  <p>I get back</p>
  
  <pre><code>{"talk":"Miaow.","parasite":null,"name":"Oggy","species":"cat"}
  </code></pre>
  
  <p>I have tried this with other more complex classes, this is just a simple example.
  I have looked in the debugger, the <code>parasite</code> value is in the value provider, the model the binder returns contains a field for the parasite.
  Can anyone see where the problem is?</p>