2015-01-16 89 views
6

我有一個內容區域將有一些塊,這些塊的某些屬性必須使用SQL查詢中的數據進行初始化,因此在控制器中我有類似這樣的內容:EpiServer - 以編程方式將塊添加到內容區域

foreach (ObjectType item in MyList) 
{ 
    BlockData currentObject = new BlockData 
    { 
     BlockDataProperty1 = item.ItemProperty1, 
     BlockDataProperty2 = item.ItemProperty2 
    }; 
    /*Dont know what to do here*/ 
} 

我需要的是將currentObject作爲塊使用,並將其添加到我在另一個塊中定義的內容區域。我試着用

myContentArea.Add(currentObject) 

但它說,因爲它期待一個IContent類型,而不能添加對象爲內容的區域。

我該如何將該物體投射到IContent

回答

8

要在EPiServer內容,您需要使用的newIContentRepository,而不是運營商的實例:

var repo = ServiceLocator.Current.GetInstance<IContentRepository>(); 

// create writable clone of the target block to be able to update its content area 
var writableTargetBlock = (MyTargetBlock) targetBlock.CreateWritableClone(); 

// create and publish a new block with data fetched from SQL query 
var newBlock = repo.GetDefault<MyAwesomeBlock>(ContentReference.GlobalBlockFolder); 

newBlock.SomeProperty1 = item.ItemProperty1; 
newBlock.SomeProperty2 = item.ItemProperty2; 

repo.Save((IContent) newBlock, SaveAction.Publish); 

之後,你就可以將塊添加到內容區域:

// add new block to the target block content area 
writableTargetBlock.MyContentArea.Items.Add(new ContentAreaItem 
{ 
    ContentLink = ((IContent) newBlock).ContentLink 
}); 

repo.Save((IContent) writableTargetBlock, SaveAction.Publish); 

EPiServer在運行時爲塊創建代理對象,並實現IContent接口。當您需要在塊上使用IContent成員時,請將其明確地轉換爲IContent

當您使用new運算符創建塊時,它們不會保存在數據庫中。另一個問題是內容區域不接受這樣的對象,因爲它們不實現IContent intefrace(您需要從IContentRepository獲得在運行時創建代理的塊)。

+0

感謝您的回答,它似乎是工作,但仍有問題,行 repo.Save(newBlock,SaveAction.Publish); 標記錯誤,說明保存的最佳重載包含一些無效參數,已嘗試 repo.Save(newBlock,SaveAction.Publish,AccessLevel.Administer); 以及IContentRepository.Save(repo,newBlock,saveAction.Publish) – rhernandez

+0

是的,看起來像是同一個'IContent'投射問題。嘗試'repo.Save((IContent)newBlock,SaveAction.Publish);' – whyleee

+0

它的工作!現在將數據顯示爲一個塊,可編輯屬性正常工作。 只是另一個問題(我不知道我是否打開另一個線程)塊正在被正確添加,但是當我去到父組件時,ContentArea看起來是空的,所以我檢查並意識到塊被添加到全局集合文件夾,我如何「告訴」組件在編輯模式下顯示到內容區域?我正在嘗試使用此解決方案http://joelabrahamsson.com/custom-rendering-of-content-areas/,但目前爲止還沒有爲我工作。 謝謝 – rhernandez

相關問題