Asp.net mvc 2 asp.net mvc强类型母版页-类型问题

Asp.net mvc 2 asp.net mvc强类型母版页-类型问题,asp.net-mvc-2,view,master-pages,strong-typing,Asp.net Mvc 2,View,Master Pages,Strong Typing,我有两个视图模型: public class MasterPageViewModel { public string Meta { get; set; } } public class Entry : MasterPageViewModel { public int EntryID { get; set; } public string Title { get; set; } public DateTime PubDate { get; set; } } 索引

我有两个视图模型:

public class MasterPageViewModel
{
    public string Meta { get; set; }
}

public class Entry : MasterPageViewModel
{
    public int EntryID { get; set; }
    public string Title { get; set; }
    public DateTime PubDate { get; set; }
}
索引页返回条目列表,因此视图中包含:

...Inherits="System.Web.Mvc.ViewPage<IEnumerable<bl.Models.Entry>>"
…Inherits=“System.Web.Mvc.ViewPage”
然后母版页包含

...Inherits="System.Web.Mvc.ViewMasterPage<bl.Models.MasterPageViewModel>"
…Inherits=“System.Web.Mvc.ViewMasterPage”
下面是我得到的错误:

传递到字典的模型项的类型为“System.Linq.EnumerableQuery`1[bl.Models.Entry]”,但此字典需要类型为“bl.Models.MasterPageViewModel”的模型项


通过在母版页上使用ViewData dictionary,我可以轻松绕过该错误,但就我而言,我更喜欢强类型方法。将来,我希望能够添加将出现在母版页上的类别和标记列表。

我有一些类似于您在我正在处理的MVC站点中描述的结构。我还没有找到一个真正令人满意的答案——在很多情况下,你感觉你需要两个不同的模型,一个用于母版页,一个用于内容页。不幸的是,MVC不是这样工作的

除了您提到的ViewData选项之外,我只遇到了一种解决方案

基类

  • 构建一个所有模型都继承的基类
  • 基类包含母版页中所需的所有属性
  • 好:这是简单的继承
  • 糟糕的是:对于传递可枚举集合之类的基本事情,最终会得到包装器方法/模型
所以在你的情况下,你最终会得到像

public class MasterPageViewModel {
    public string Meta { get; set; }
}

public class Entry : MasterPageViewModel {
  public IEnumerable<bl.Models.EntryItem> Items {get; set }
}

public class EntryItem{
    public int EntryID { get; set; }
    public string Title { get; set; }
    public DateTime PubDate { get; set; }
}
公共类MasterPageViewModel{
公共字符串元{get;set;}
}
公共类条目:MasterPageViewModel{
公共IEnumerable项{get;set}
}
公共类入口项{
public int EntryID{get;set;}
公共字符串标题{get;set;}
public DateTime PubDate{get;set;}
}
你的索引页看起来像

...Inherits="System.Web.Mvc.ViewPage<bl.Models.Entry>"
…Inherits=“System.Web.Mvc.ViewPage”
这有点让人头疼,因为你最终会有很多小模特。然而,一旦我习惯了,我就不再去想它了

嗯,


-eric

嗨eric,我使用Html.RenderAction解决了这个问题,没有创建额外的视图模型。我不想重复我自己的话,把所有常见的动作都放在separe控制器:CommonController中。然后,在母版页中,我使用Html.RenderAction(“Categories”、“Common”)或Html.RenderAction(“Tags”、“Common”)。每个操作都是强类型的,并返回部分视图。