0

我正在使用 MVC 3 和 EF 构建博客。我已经创建了所有模型,并且一切正常。我决定我想要一个正确的导航栏,其中包含最新的帖子、评论和所有类别。我认为这将是使用 ViewModel 的好地方。

我使用文章、评论和类别作为收藏创建了 ViewModel。我创建了一个控制器并执行了我的 linq 来填充 ViewModel 并创建了一个部分共享视图。当我尝试使用 HTML.Partial 或诸如此类的东西时,我得到:

传递到字典中的模型项是 System.Collections.Generic.Lists 类型,但期望...

我在其中使用的页面是基于不同模型的强类型页面。

我做错了什么,也许我只是一个新手,或者我走错了路……救命!?

编辑:

我得到的错误突出显示了我调用部分视图的行

@HTML.Partial("_SideBar")

SideBar 使用 SideBarViewModel,但我从中调用它的常规页面(“Index.vbhtml”)使用 ArticleModel。我没有看到您的示例在这种情况下如何工作。我想在一堆页面中重用它......

侧边栏视图模型:

Public Class SidebarViewModel
    Public Property RecentPosts As ICollection(Of Article)
    Public Property RecentComments As ICollection(Of Comment)
    Public Property Categories As ICollection(Of Category)
End Class

ArticleModel:公共类文章公共属性 ArticleId 作为整数公共属性作者作为字符串

    <DisplayFormat(DataFormatString:="{0:D}")>
    Public Property CreatedOn As DateTime

    <DisplayFormat(DataFormatString:="{0:D}")>
    Public Property LastModified As DateTime

    Public Property Content As String
    Public Property Title As String
    Public Property Excerpt As String
    Public Property Status As String
    Public Property IsPublic As Boolean

    Public Overridable Property Categories As ICollection(Of Category)
    Public Overridable Property Tags As ICollection(Of Tag)
    Public Overridable Property Comments As ICollection(Of Comment)
End Class
4

2 回答 2

1

创建局部视图时,您需要将相关模型传递给它。

<% Html.renderpartial("partial", model.partialViewsModel); %>

因此,您的 ViewModel 需要包含一个模型,该模型会传递给局部视图,并且是局部视图所期望的类型。

所以view1的模型可能是;

public class View1()
{
  public PartialModel partielViewsModel { get;set;}
  public string title {get;set;}
}

view2 的模型可能是;

public class View2()
{
  public PartialModel partielViewsModel { get;set;}
  public int numberofthings {get;set;}
}
于 2012-08-16T05:26:54.303 回答
0

这个问题有一个很好的解决方案,使用控制器基类、单独的视图模型和自定义过滤器属性:

http://blog.bitdiff.com/2012/05/sharing-common-view-model-data-in.html

于 2014-03-31T14:05:33.867 回答