EpiServer - Add block to a content area programmatically

前端 未结 1 988
失恋的感觉
失恋的感觉 2021-01-12 17:44

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

相关标签:
1条回答
  • 2021-01-12 18:22

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

    0 讨论(0)
提交回复
热议问题