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

本文关键字:自定义 类型 文档 | 更新日期: 2023-09-27 17:52:35

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

public partial class Whitepaper : TreeNode { }
public partial class WhitepaperProvider { }

如果我使用提供程序直接查询特定文档,这些类工作得很好,例如:

WhitepaperProvider.GetWhitepapers().TopN(10);

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

// 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;

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


正如答案所提到的,只要一个类已经为当前页面类型注册,使用as就可以工作。我没有期望这工作,因为我假设DocumentContext。CurrentDocument总是返回一个TreeNode(因此你会有一个逆变问题);如果有一个为页面类型注册的类,它将返回该类的实例,从而允许您使用as

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

应该像…一样简单

var stronglyTyped = DocumentContext.CurrentDocument as Whitepaper

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

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

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

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

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)