我有这将有一些块,这些块的一些属性必须从SQL查询的数据进行初始化,所以在控制器我有一些像这样的内容区域:
foreach (ObjectType item in MyList)
{
BlockData currentObject = new BlockData
{
BlockDataProperty1 = item.ItemProperty1,
BlockDataProperty2 = item.ItemProperty2
};
/*Dont know what to do here*/
}
Run Code Online (Sandbox Code Playgroud)
我需要什么,是一起工作currentObject作为一个块,并将其添加到我已经在另一个块定义的内容区域.我试过用
myContentArea.Add(currentObject)
Run Code Online (Sandbox Code Playgroud)
但它表示无法将对象添加到内容区域,因为它期望一种IContent类型.
如何将该对象转换为IContent?
why*_*eee 10
要在EPiServer中创建内容,您需要使用IContentRepository而不是new运算符的实例:
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);
Run Code Online (Sandbox Code Playgroud)
之后,您将能够将块添加到内容区域:
// 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);
Run Code Online (Sandbox Code Playgroud)
EPiServer在运行时为块创建代理对象,并实现IContent接口.当您需要IContent在块上使用成员时,将其强制转换为IContent显式.
使用new运算符创建块时,它们不会保存在数据库中.另一个问题是内容区域不接受这样的对象,因为它们不实现IContentintefrace(您需要从IContentRepository运行时获取创建代理的块).
| 归档时间: |
|
| 查看次数: |
5592 次 |
| 最近记录: |