【问题标题】:Inheritance and Strongly Typed Views继承和强类型视图
【发布时间】:2011-06-03 14:42:11
【问题描述】:

我有一个包含一些属性和方法的抽象类 foo。我还有许多实现 foo 的类,例如 barfoofoobar

为了在多个不同的视图上安全地重写相同的代码,我创建了一个强类型的局部视图

@model List<foo>
@foreach (var x in Model) {
<div> x.SomeProperty </div>
}

可悲的是,当我尝试用

调用此视图时
@{ Html.RenderPartial("PartialView", List<Foobar>); }

我收到以下错误

传入字典的模型项的类型为 System.Collections.Generic.List1[Namespace.Models.Foobar]', but this dictionary requires a model item of type 'System.Collections.Generic.List1[Namespace.Models.Foo]'。

我正在尝试做的事情是否可行,还是我只需要复制代码?

【问题讨论】:

    标签: c# asp.net-mvc inheritance razor


    【解决方案1】:

    完全尝试您正在尝试的东西是不可能的。如果您所做的只是枚举集合(而不是修改它),您可以更改为以下内容,一切都应该没问题:

    @model IEnumerable<foo>
    @foreach (var x in Model) {
        <div> x.SomeProperty </div>
    }
    

    如果你仔细想想,这个问题是相当容易理解的。

    您的模型是List&lt;foo&gt;。这意味着应该完全可以说Model.Add(new Barfoo());

    您正在尝试将List&lt;Foobar&gt; 作为模型传递。显然,Model.Add(new Barfoo()); 在这种情况下会失败,因为这是不可能的。

    使用像 IEnumerable 这样的协变接口可以让您完全按照自己的需要去做。

    【讨论】:

    • 您不能将项目添加到 IEnumerable (因为 IENumerable 没有 Add() 方法)而是 ICollection 。因此,传入的模型必须实现 ICollection 以允许向其添加项目。
    • @Marius - 正确,但没有充分的理由允许在模型中添加项目(除非您使用模型绑定将更新的集合发布到服务器,在这种情况下,您应该使用 ViewModel 类)。
    【解决方案2】:

    你可以这样做:

    @{ Html.RenderPartial("ParialView", list.Cast<Foo>().ToList()); }
    

    List&lt;FooBar&gt; 的运行时类型与List&lt;Foo&gt; 不同,并且由于您没有使用协变接口,因此不能假设它会接受隐式转换。

    【讨论】:

      【解决方案3】:

      List&lt;Foo&gt; does not inherit from List&lt;Foobar&gt; 这就是为什么这不起作用...

      【讨论】:

        【解决方案4】:

        如何为部分视图提供 Foo 集合而不是 FooBar 集合?

        @{ Html.RenderPartial("PartialView", MyFoobBarList.Cast<Foo>().ToList()); }
        

        (顺便问一下,你真的需要这份清单吗?)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-01-27
          • 1970-01-01
          • 1970-01-01
          • 2012-04-21
          • 2019-01-08
          • 2010-11-25
          相关资源
          最近更新 更多