title: asp.net mvc model inheritance for "simple forms"
body: <p>How would you implement this ? </p>
  
  <p>I have the following model :</p>
  
  <pre><code>class Something
  {
       public string Label { get; set; }
       public DateTime Date1 { get; set; }
  }
  
  class SomethingStage2 : Something
  {
       public DateTime Date2 { get; set; }
  }
  
  class SomethingStage3 : SomethingStage2
  {
       public DateTime Date3 { get; set; }
  }
  </code></pre>
  
  <p>And the following editor templates :</p>
  
  <p>EditorTemplates\Something</p>
  
  <pre><code>&lt;%@ Control Language="C#" Inherits="ViewUserControl&lt;Something&gt;" %&gt;
  &lt;%= Html.Hidden( "TypeName", Model.GetType() ) %&gt;
  &lt;%= Html.EditorFor( x =&gt; x.Label ) %&gt;
  &lt;%= Html.EditorFor( x =&gt; x.Date1 ) %&gt;
  </code></pre>
  
  <p>EditorTemplates\SomethingStage2</p>
  
  <pre><code>&lt;%@ Control Language="C#" Inherits="ViewUserControl&lt;SomethingStage2&gt;" %&gt;
  &lt;% Html.RenderPartial("EditorTemplates/Something.ascx" %&gt;
  &lt;%= Html.EditorFor( x =&gt; x.Date2 ) %&gt;
  </code></pre>
  
  <p>EditorTemplates\SomethingStage3</p>
  
  <pre><code>&lt;%@ Control Language="C#" Inherits="ViewUserControl&lt;SomethingStage3&gt;" %&gt;
  &lt;% Html.RenderPartial("EditorTemplates/SomethingStage2.ascx" %&gt;
  &lt;%= Html.EditorFor( x =&gt; x.Date3 ) %&gt;
  </code></pre>
  
  <p>For updating, I have the following controller method : </p>
  
  <pre><code>public ActionResult Update( Something model );
  </code></pre>
  
  <p>Technically, it works very well. </p>
  
  <p>Update : for handling the different subclasses of the model, I've borrowed this idea : 
  <a href="http://www.codinginstinct.com/2010/03/aspnet-mvc-and-convention-based-forms.html" rel="nofollow noreferrer">http://www.codinginstinct.com/2010/03/aspnet-mvc-and-convention-based-forms.html</a></p>
  
  <pre><code>public class CustomModelBinder : DefaultModelBinder
  {
      public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
      {
          var typeName = bindingContext.ValueProvider.GetValue("TypeName");
          var type = Type.GetType(reportFormTypeName.AttemptedValue);
          var model = bindingContext.ModelMetadata.Model;
          bindingContext.ModelMetadata = new ModelMetadata(ModelMetadataProviders.Current, 
              bindingContext.ModelMetadata.ContainerType,
              () =&gt; model, type , bindingContext.ModelMetadata.PropertyName);
  
          return base.BindModel(controllerContext, bindingContext);
      }
  }
  </code></pre>
  
  <p>Update : If Date3 should go between Label and Date1, this approach won't work, of course. That's why it is for simple forms. And it is a big time saver, </p>
  
  <p><strike>Is this approach correct, for simple cases, where edit forms are straightforward ?</strike> I'm just wondering if it is "right" to do it this way. If not, how would you implement this ?</p>