EpiServer - add a block to the content area programmatically

I have a content area that will have some blocks, some attributes of these blocks must be initialized with data from the 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 the content area that I defined in another block. I tried to use

 myContentArea.Add(currentObject) 

but he says he cannot add an object to the content area because he expects an IContent type.

How can I pass this object to IContent ?

+6
source share
1 answer

To create content in EPiServer, you need to use an instance of IContentRepository instead of the 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 can 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 at runtime and implements the IContent interface. When you need to use the IContent element in a block, explicitly specify its IContent .

When creating blocks using the new operator, they are not stored in the database. Another problem is that the content area does not accept such objects, since they do not implement IContent intefrace (you need to get blocks from IContentRepository that proxies create at runtime).

+8
source

Source: https://habr.com/ru/post/981133/


All Articles