Pass subclass of generic model to razor view

前端 未结 3 980
有刺的猬
有刺的猬 2020-12-28 20:25

The Big Picture:

I have found what seems like a limitation of Razor and I am having trouble coming up with a good way around it.

相关标签:
3条回答
  • 2020-12-28 20:49

    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>
    
    0 讨论(0)
  • 2020-12-28 20:53

    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"

    0 讨论(0)
  • 2020-12-28 21:02

    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.

    0 讨论(0)
提交回复
热议问题