2016-06-28 99 views
0

目前,我在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; 

如何使用我的自定義頁面類型的類當前文檔?


UPDATE

的答案使用as作品只要一類被註冊爲當前頁面類型提到。我沒有想到這個工作,因爲我認爲DocumentContext.CurrentDocument總是返回一個TreeNode(因此你會有一個逆變問題);如果有一個爲頁面類型註冊的類,它將返回一個類的實例,從而允許您使用as

+0

你試過投當前文檔作爲您的自定義類?:白皮書currentWhitepaperDocument = DocumentContext。 CurrentDocument作爲白皮書 –

回答

1

應儘可能簡單as ...

var stronglyTyped = DocumentContext.CurrentDocument as Whitepaper 

...只要您使用註冊白皮書類作爲文檔類型屬性上CMSModuleLoader例如:

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

這是關於連接最多強類型的頁面類型的對象一個很好的博客文章:http://johnnycode.com/2013/07/15/using-strongly-typed-custom-document-type-classes/

+0

這絕對有效,但我沒有想到它。我認爲DocumentContext.CurrentDocument總是返回一個TreeNode,但是如果有一個爲頁面類型註冊的類將會自動返回該類。我會更新我的帖子,謝謝! – KingOfTheWood

0

你可以擴展你的部分類(不修改生成的文件,創建一個部分爲原件),例如:

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) 
相關問題