ASP.NET MVC3 EditorFor that looks for inheritance

Today I ran into issue with MVC 3 where a view with a model type TModel won’t check to see if the model’s instance is a subclass of TModel, resulting in any attributes on overridden properties being ignored. This is because the metadata is read from the type specified in the view, and not the actual instance.

For example, with the following class structure and view will never render “SomeProperty” as “required”, even if the model is an instance of InheritedClass.

Classes:

public class BaseClass 
{
  public virtual string SomeProperty { get; set; }
}

public class InheritedClass : BaseClass
{
  [Required()]
  public override string SomeProperty { get; set; }
}

ASPX Page:

<%@ Page Language="C#" Inherits="ViewPage<BaseClass>" %>

<%:Html.EditorFor(m => m.SomeProperty)%>

I think there may be a couple of different way to resolve this issue, though I came up with a solution that creates a new EditorFor override, takes the Expression<> and HtmlHelper<> and rebuilds them based on the inherited type and calls the original EditorFor internally.

Here is my final solution

Comments are closed.