跳轉至內容

Umbraco/示例和文章/以程式設計方式建立 Umbraco 頁面

來自華夏公益教科書,面向開放世界的開放書籍

以程式設計方式建立 Umbraco 頁面

[編輯 | 編輯原始碼]

這基於 http://www.umbraco.org/frontpage/documentation/implementingnetcontrols/creatingumbracopagesprogrammatically.aspx 上的原始文章

使用 Umbraco api(業務邏輯)可以輕鬆地以程式設計方式建立新頁面。只需確保您引用了 umbraco.dll(或如果執行的是 2.1:cms.dll 和 businesslogic.dll)。

以下幾行示例程式碼展示瞭如何做到這一點。

using umbraco.cms.businesslogic.web;
 
// The documenttype that should be used, replace 10 with the id of your documenttype

DocumentType dt = new DocumentType(10);
 
// The umbraco user that should create the document, 
// 0 is the umbraco system user, and always exists

umbraco.BusinessLogic.User u = new umbraco.BusinessLogic.User(0);
 
// The id of the parent document
 
int parent = 100;
 
// Create the document
 
Document d = Document.MakeNew("My weblog post", dt, u, parent);
 
// Add values to the generic properties of the document 
// (where bodyText is the alias of your property)

d.getProperty("bodyText").Value = "Lorem Ipsum";
 
// Set the publish status of the document and there by create a new version 

d.Publish(u); 

// Tell the runtime environment to publish this document 

umbraco.library.PublishSingleNode(d.Id);

在 Umbraco 版本 2.1 中,您可以使用 DocumentType.GetByAlias(string Alias),因此您不再依賴於識別符號。這是最佳實踐,對於使您的程式碼可重用非常重要。如果您執行的是 2.0,請確保透過建立公共屬性可以從 Umbraco 中更改文件型別的 id。

華夏公益教科書