Pass subclass of generic model to razor view

前端 未结 3 1016
有刺的猬
有刺的猬 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 where T : BaseBarType
    {
    }
    

    And derive your BaseFooModel from the above interface.

    public abstract class BaseFooModel : IFooModel 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
    

提交回复
热议问题