Pass subclass of generic model to razor view Pass subclass of generic model to razor view asp.net asp.net

Pass subclass of generic model to razor view


You need to introduce an interface with a covariant generic type parameter into your class hierarchy:

public interface IFooModel<out T> where T : BaseBarType{}

And derive your BaseFooModel from the above interface.

public abstract class BaseFooModel<T> : IFooModel<T> where T : BaseBarType{}

In your controller:

[HttpGet]public ActionResult Index(){    return View(new MyFooModel());}

Finally, update your view's model parameter to be:

@model IFooModel<BaseBarType>


Using interfaces-based models was deliberately changed between ASP.NET MVC 2 and MVC 3.

You can see here

MVC Team:

Having interface-based models is not something we encourage (nor, given the limitations imposed by the bug fix, can realistically support). Switching to abstract base classes would fix the issue.

"Scott Hanselman"


The problem you are experiencing is not a Razor error, but a C# error. Try to do that with classes, and you'll get the same error. This is because the model is not BaseFooModel<BaseBarType>, but BaseFooModel<MyFooModel>, and an implicit conversion cannot happen between the two. Normally, in a program you'd have to do a conversion to do that.

However, with .NET 4, introduced was contravariance and covariance, which sounds like the ability of what you are looking for. This is a .NET 4 feature only, and I honestly don't know if Razor in .NET 4 makes use of it or not.