Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Kasper 13 posts 84 karma points
    Mar 09, 2022 @ 09:59
    Kasper
    0

    How can I identify data type of BlocklistModel in code?

    Is there any way to check the underlying datatype of a blocklist in code? Let's say I have created a blocklist data type and called it fooBlocklist and another one called barBlocklist and added a property to a document type which uses the fooBlocklist.

    When accessing this property in code, I get a BlockListModel, and I can loop through the BlockListItems in the block, but is there any way to determine if the BlockListModel is using the barBlocklist or the fooBlocklist?

    Something like this in pseudo:

    if (model.myBlockListProperty is BlockListModel<fooBlockList>)
    {
        //do stuff
    }
    

    So far, my best approach has been to check if all blockitems inside the BlockListModel are of a certain type, because I know I only have one blocklist with this specific configuration of blocks, but this approach doesn't work if the blocklist is empty.

  • Ambert van Unen 175 posts 819 karma points c-trib
    Mar 10, 2022 @ 22:25
    Ambert van Unen
    0

    but this approach doesn't work if the blocklist is empty.

    You could easily add a

    if (myBlockList.Any()) 
    

    To check if there are any items ofcourse ;-)

    I've been trying this myself aswell, and I think it's not directly possible like you want it. It's probably also the reason Umbraco provides the demo with rendering the items in the blocklist as seperate components:

    @if (Model?.Any() == true)
    {
         foreach (var block in Model)
         {
             if (block?.ContentUdi == null) { continue; }
             @(await Component.InvokeAsync(block.Content.ContentType.Alias, block))
         }
     }
    

    This way you avoid the issue entirely, and always render a component with the correct model.

    However! You could do exactly as Umbraco does but in a switch/case for example:

    switch (blockListItem.Content.ContentType.Alias)
            {
                case LinkItemElement.ModelTypeAlias
                    : // do this
                default:
                    // else default do this
                break;
            }
    
Please Sign in or register to post replies

Write your reply to:

Draft