Try our conversational search powered by Generative AI!

How to get a block by id from specific folder in code?


I'm facing an issue with getting block in code, can somebody help me??

scenario: I want to get a block(step_block) which is in folder("test folder/new folder/blocks"), how I can get this in code? (POV: I'm running scheduling job, which will update content to one field with above block)

if somebody knows this, please go ahead

Edited, Apr 20, 2023 7:35

If you have a shared block and it's not referenced in your current page and you want to read the best thing is to create some sort of settings (such as on home page) with a ContentReference. 

Then set that link to the block and read that reference from the settings allowing to to load that block.

Apr 20, 2023 10:19

Sure you can, you can traverse the tree by fetching all children using contentLoader GetChildren. The folder object is called ContentFolder

Here's an example

using Microsoft.AspNetCore.Mvc;

namespace alloyfrankenstein.Controllers
    public class FrankensteinController : ControllerBase
        private readonly IContentLoader _contentLoader;

        public FrankensteinController(IContentLoader contentLoader)
            _contentLoader = contentLoader;

        public IActionResult Get(string searchPath)
            var blockRoot = _contentLoader.Get<ContentFolder>(ContentReference.GlobalBlockFolder);
            var searchRoot = blockRoot;
            foreach (var path in searchPath.Split('/'))
                var content = _contentLoader.GetChildren<IContent>(searchRoot.ContentLink).FirstOrDefault(x => x.Name.Equals(path, StringComparison.CurrentCultureIgnoreCase));
                if (content is ContentFolder contentFolder)
                    searchRoot = contentFolder;

                if (content is BlockData blockData)
                    var block = (IContent)blockData;
                    return Ok($"{block.Name} - {block.ContentLink.ID}");

                // no path found, exit

            return Ok("No block found in path");

In the sample site Alloy this structure

Could be fetched by searching for "Alloy Track/Test/Events list"

In the code the last element is the actual block. Simply modify according to your needs.

Edited, Apr 20, 2023 13:18
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* 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.