我有一个内容区域,其中有一些块,这些块的某些属性必须使用 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
type.
我怎样才能将该对象转换为IContent
?
要在 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
接口(你需要从IContentRepository
它在运行时创建代理)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)