如何为当前文档使用自定义页面类型 class

How to use custom page type class for current document

目前,我在 CMS 中有几种自定义页面类型。为了在处理文档时具有类型安全性,我使用内置代码生成器为每种页面类型创建 classes。例如,我有一个名为 Whitepaper 的页面类型,Kentico 代码生成器生成了两个 classes:

public partial class Whitepaper : TreeNode { }

public partial class WhitepaperProvider { }

如果我使用提供商直接查询特定文档,这些 classes 非常有用,例如:

WhitepaperProvider.GetWhitepapers().TopN(10);

但是,我希望能够对当前文档使用 Whitepaper class,而不必使用 WhitepaperProvider 重新查询文档。在这种情况下,我有一个用于白皮书的自定义页面模板,在后面的代码中,我希望能够为其使用自定义 class:

// This is what I'm using
TreeNode currentDocument = DocumentContext.CurrentDocument;
var summary = currentDocument.GetStringValue("Summary", string.Empty);

// This is what I'd like to use, because I know the template is for whitepapers
Whitepaper currentWhitepaperDocument = // what goes here?
summary = currentWhitepaperDocument.Summary;

如何为当前文档使用我的自定义页面类型 class?


更新

正如答案中提到的,只要为当前页面类型注册了 class,使用 as 就可以工作。我没想到这会起作用,因为我假设 DocumentContext.CurrentDocument 总是 returned 一个 TreeNode(因此你会有一个逆变问题);如果为页面类型注册了 class,它将 return 一个 class 的实例,从而允许您使用 as.

您可以扩展您的部分 class(不要修改生成的文件,为原始文件创建一个部分),示例:

public partial class Whitepaper
{
    public Whitepaper CreateFromNode(TreeNode node)
    {
        //You should choose all necessary params in CopyNodeDataSettings contructor
        node.CopyDataTo(this, new CopyNodeDataSettings());
        //You should populate custom properties in method above.
        //this.Status = ValidationHelper.GetString(node["Status"], "");
        return this;
    }
}

使用方法:

new Whitepaper().CreateFromNode(DocumentContext.CurrentDocument)

应该像...一样简单

var stronglyTyped = DocumentContext.CurrentDocument as Whitepaper

...只要您使用 CMSModuleLoader 上的 DocumentType 属性将白皮书 class 注册为文档类型,例如:

[DocumentType("WhitepaperClassName", typeof(Namespace.To.Whitepaper))]

这是一篇关于连接强类型页面类型对象的好博客post:http://johnnycode.com/2013/07/15/using-strongly-typed-custom-document-type-classes/