Add block to ContentArea programmatically C# Episerver 11.x

GR
GR
Vote:
 

Hi Team,

I was trying to add the blocks to the ContentArea programmatically and used the following code.

DisplayOption threw an exception of type 'System.NotImplementedException'

//Save the page

contentRepository.Save(myPage, EPiServer.DataAccess.SaveAction.Publish,EPiServer.Security.AccessLevel.Read);

//Save the Block

ContentAssetHelper contentAssetFolder = ServiceLocator.Current.GetInstance<ContentAssetHelper>();
var contentAsset = contentAssetFolder.GetOrCreateAssetFolder(myPage.ContentLink);

var newBlock = contentRepository.GetDefault<RawHTML>(parentLink: contentAsset.ContentLink);

var writableClonePage = (InnerPage)myPage.CreateWritableClone();

var rep = ServiceLocator.Current.GetInstance<IContentRepository>();

newBlock.HTMLContent = new XhtmlString(WebUtility.HtmlDecode(c.Content));

IContent icontentBlock = (IContent)newBlock;
icontentBlock.Name = c.PaneName;

ContentReference savedReference = rep.Save(icontentBlock, SaveAction.Publish, AccessLevel.NoAccess);

//Add the Block to ContentArea

var AddblockItem = new ContentAreaItem
{
ContentGuid = Guid.NewGuid(),
ContentLink = savedReference
};

writableClonePage.ContentArea.Items.Add(AddblockItem);
rep.Save((IContent)writableClonePage, SaveAction.Publish, AccessLevel.Read);

Can you please help me where I made a mistake?

Thanks

Ashley

#246027
Dec 24, 2020 16:12
Praful Jangid - Dec 25, 2020 7:45
Can you paste here the exception with details of in which line you are getting exception?
GR - Dec 28, 2020 13:51
Hi Praful,

I am getting error((DisplayOption threw an exception of type 'System.NotImplementedException')) on this below line.

writableClonePage.ContentArea.Items.Add(AddblockItem);

Thanks
Ashley
Vote:
 

Hi,

It looks like your Content Area is null?

Could you add the following line:

writableClonePage.ContentArea = new ContentArea();

Also, where did you get this code sample from? You shouldn't set:

ContentGuid = Guid.NewGuid()

/Jake

#246174
Edited, Dec 29, 2020 14:36
Vote:
 

Hi, most probably the solution is what Jake suggested you in his comments. I did the same mistake to not initialize the content area type property. Before adding items into that, you can check if the content area is null then initialize it, otherwise you can just add items.

Please let us know if that not fixes your issue.

#246408
Jan 05, 2021 12:20
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.