EpiServer - 以编程方式将块添加到内容区域
EpiServer - Add block to a content area programmatically
我有一个包含一些块的内容区域,这些块的一些属性必须使用来自 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
?
要在 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
interfrace(您需要从 IContentRepository
获取块,这会在运行时创建代理)。
我有一个包含一些块的内容区域,这些块的一些属性必须使用来自 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
?
要在 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
interfrace(您需要从 IContentRepository
获取块,这会在运行时创建代理)。