Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EpiServer - Add block to a content area programmatically

Tags:

episerver

I have a content area which will have some blocks, some attributes of these blocks must be initialized with data from a SQL query, so in the controller I have something like this:

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

What I need, is to work with currentObject as a block, and add it to a content area I have defined in another block. I tried using

myContentArea.Add(currentObject)

but it says it can't add an object into a content area because it is expecting for an IContent type.

How can I cast that object into an IContent?

like image 813
rhernandez Avatar asked Jan 16 '15 22:01

rhernandez


1 Answers

To create content in EPiServer you need to use an instance of IContentRepository instead of new operator:

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);

After that you will be able to add the block to the content area:

// 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 creates proxy objects for blocks in runtime and they implement IContent interface. When you need to use IContent member on a block, cast it to IContent explicitly.

When you create blocks using new operator, they are not saved in the database. Another problem is content area doesn't accept such objects, because they don't implement IContent intefrace (you need to get blocks from IContentRepository which creates proxies in runtime).

like image 111
whyleee Avatar answered Sep 19 '22 10:09

whyleee