Posted by Phil in Uncategorized
on May 18th, 2012 | Comments Off on 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; }
}
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.
About Me
I'm primarily a .NET developer, an architect and a rationalist. I dabble in F#, node.js and other tools and techniques that might make me a better developer and I'd like to share what I learn.