EpiServer - 以编程方式将块添加到内容区域

时间:2015-01-16 22:40:04

标签: episerver

我有一个内容区域,它有一些块,这些块的一些属性必须用SQL查询中的数据初始化,所以在控制器中我有这样的东西:

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

1 个答案:

答案 0 :(得分: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);

之后,您将能够将该块添加到内容区域:

// 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获取在运行时创建代理的块)。

相关问题