-->

How to use custom page type class for current docu

2019-09-06 10:38发布

问题:

Currently, I have several custom page types within the CMS. In order to have type safety when working with documents, I used built-in code generator to create classes for each page type. For example, I have a page type called Whitepaper and the Kentico code generator generated two classes:

public partial class Whitepaper : TreeNode { }

public partial class WhitepaperProvider { }

These classes work great if I'm directly querying for specific documents using the provider such as:

WhitepaperProvider.GetWhitepapers().TopN(10);

However, I want to be able to use the Whitepaper class for the current document without having to re-query for the document using the WhitepaperProvider. In this case I have a custom page template for Whitepapers and in the code behind I want to be able to use the custom class for it:

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

How do I use my custom page type class for the current document?


UPDATE

As the answer mentions using as works as long as a class has been registered for the current page type. I didn't expect this to work because I assumed DocumentContext.CurrentDocument always returned a TreeNode (thus you'd have a contravariance problem); if there is a class registered for the page type it will return an instance that class instead thus allowing you to use as.

回答1:

Should be as simple as...

var stronglyTyped = DocumentContext.CurrentDocument as Whitepaper

...as long as you've registered your Whitepaper class as a document type by using the DocumentType attribute on CMSModuleLoader e.g.:

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

This is a good blog post about wiring up strongly typed page type objects: http://johnnycode.com/2013/07/15/using-strongly-typed-custom-document-type-classes/



回答2:

you can extend your partial class (do not modify the generated file, create a partial for original), example:

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

How to use it:

new Whitepaper().CreateFromNode(DocumentContext.CurrentDocument)


标签: c# kentico