umbraco/Umbraco.Headless.Client.Net

Replace Nested Content with Block List

Opened this issue · 3 comments

Issue description

In the code samples Nested Content is used and delivered as IEnumerable<IElement>:

However I can't find any examples how to get content from Block List property and how to loop the blocks or just select content as IEnumerable<IElement> .. and then in razor view or controller cast a specific block type?

Since Nested Content is deprecated and will be removed in an upcoming release or Umbraco (and probably in Heartcore as well), I think it should be practise as use Block List instead.

Based on the roadmap it seems Block Grid soon is supported as well:
https://umbraco.com/products/knowledge-center/roadmap/

@rasmusjp do you know about this? 😊

We currently don't ship with any models for the block list but you can add one your self. It could look something like this:

public class BlockListItem
{
    public Element Content { get; set; }
    public Element? Settings { get; set; }
}

and then use it like this

public class MyModel : Content
{
    public IEnumerable<BlockListItem> MyBlocks { get; set; }
}

If your custom model inherits from Element and has the same name as the Document Type alias or has the ElementModelAttribute with the Document Type alias then you should be able to cast Content or Settings to that model in you view

Hi @rasmusjp

Thanks for your help - it works! 🥳🎉

I think it would be great it the .NET Client shipped with BlockListItem model and soon probably BlockGridtem as well.
However for now I have the following:

public class BlockListItem
{
    public Element Content { get; set; } = null!;
    public Element? Settings { get; set; }
}

a ProductPage document type with a BlockList sections.

public class ProductPage : Content, IHideInNavigation
{
    public string Sku { get; set; }

    public decimal Price { get; set; }

    public int Stock { get; set; }

    public IEnumerable<MediaWithCrops> Images { get; set; }

    public IEnumerable<Content> Categories { get; set; }

    public IEnumerable<BlockListItem> Sections { get; set; }

    [JsonProperty("umbracoNaviHide")]
    public bool HideInNavigation { get; set; }

    public bool InStock() => Stock > 0;
}

and then a BlockText model reflecting the text block.

public class BlockText : Element
{
    [JsonConverter(typeof(HtmlContentConverter))]
    public IHtmlContent? Text { get; set; }
}

finally I have this in the product page razor view:

@if (Model.Sections.Any())
{
    foreach (var block in Model.Sections)
    {
        if (block.Content is BlockText blockText)
        {
            <div>
                @Html.Raw(blockText.Text)
            </div>
        }
    }
}

image

image

image