Pass subclass of generic model to razor view

jeascancy

New Member
Let's say I have a model like this:\[code\]public abstract class BaseFooModel<T> where T : BaseBarType{ // ...}\[/code\]And a subclass like this:\[code\]public class MyFooModel : BaseFooModel<MyBarType>{ // ...}public class MyBarType : BaseBarType{ // ...}\[/code\]I want to be able to pass \[code\]MyFooModel\[/code\] into a razor view that is defined like this:\[code\]// FooView.cshtml@model BaseFooModel<BaseBarType>\[/code\]But, that doesn't work. I get a run-time error saying that \[code\]FooView\[/code\] expects \[code\]BaseFooModel<BaseBarType>\[/code\] but gets \[code\]MyFooModel\[/code\]. I tried this out in non-razor land to see if the same is true, which it is. I had to use a template param in the View to get it to work. Here is that non-razor view:\[code\]public class FooView<T> where T : BaseBarType{ BaseFooModel<T> Model; public FooView(BaseFooModel<T> model) { Model = model; }}\[/code\]With that structure, the following does work:\[code\]new FooView<MyBarType>(new MyFooModel());\[/code\]But how can I do that with Razor? It seems like I can't. Is there any way around this? Let me know if I can provide more info. I'm using .NET 4 and MVC 3.
 
Back
Top