简体   繁体   English

强类型视图

[英]Strongly typed views

is it possible to pass derived types where base types are expected to strongly typed views? 是否可以在期望基本类型为强类型视图的地方传递派生类型?

Ie

  1. Products/List 产品/清单
  2. News/List 新闻/列表

where "list" view Inherits System.Web.Mvc.ViewPage<Model<BaseList>> 其中“列表”视图继承System.Web.Mvc.ViewPage<Model<BaseList>>

controller renders view ie View("List", ProductsList) 控制器呈现视图,即View(“ List”,ProductsList)


edited 已编辑

return View("List", new Model<ProductsList>());
Model<T> where T : IMyList 
ProductsList : BaseList
NewsList : BaseList
BaseList : IMyList

where ProductsList & NewsList : BaseList 其中ProductsList和NewsList:BaseList

compiles fine but get a runtime error about differing model types. 可以正常编译,但是会遇到有关不同模型类型的运行时错误。

If this not possible what is the best way to accomplish this rather than creating n no of views ? 如果无法做到这一点,而不是不创建视图,最好的方法是什么?

I think (but am not sure) this has to do with Covariance . 我认为(但不确定)这与Covariance有关

How I'm doing this is create a strongly typed viewData like for example this: 我这样做的方法是创建一个强类型的viewData,例如:

public class YourViewData: System.Web.Mvc.ViewDataDictionary
{
    public IMyList TheList { get; set; }
}

You can then make a ViewPage that you call like 然后,您可以像这样创建一个ViewPage

return View("List", new YourViewData(){TheList = new ProductList(){abunchOfItems});

Disclaimer: All freehand code 免责声明:所有手绘代码

Your question is a little unclear, but I guess it has to do with you having an IList<Base> in your model and you want to pass an IList<Derived>. 您的问题尚不清楚,但是我想这与您在模型中具有IList <Base>以及您要传递IList <Derived>有关。 This is not possible, but in C#4 you can pass an IEnumerable<Derived> instead of an IEnumerable<Base>. 这是不可能的,但是在C#4中,您可以传递IEnumerable <Derived>而不是IEnumerable <Base>。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM