【问题标题】:asp.net mvc strongly typed master page - problem with typesasp.net mvc 强类型母版页 - 类型问题
【发布时间】:2011-02-08 11:32:56
【问题描述】:

我有两个视图模型:

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.ViewMasterPage<bl.Models.MasterPageViewModel>"

这是我得到的错误:

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

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

【问题讨论】:

    标签: asp.net-mvc-2 view master-pages strong-typing


    【解决方案1】:

    我有一些类似于您在我现在正在处理的 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; }
    }
    

    您的索引页面看起来像......

    ...Inherits="System.Web.Mvc.ViewPage<bl.Models.Entry>"
    

    这有点让人头疼,因为你最终会得到很多小模型。然而,一旦我习惯了它,我就不再去想它了。

    HTH,

    -埃里克

    【讨论】:

    • 嗨,Eric,我使用 Html.RenderAction 解决了这个问题,没有创建额外的 ViewModel。我不想重复自己,并将所有常见的操作放在单独的控制器中:CommonController。然后,在母版页中,我使用 Html.RenderAction("Categories", "Common") 或 Html.RenderAction("Tags", "Common")。每个动作都是强类型并返回部分视图。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多