Search code examples
.netblazorcontentful

Getting value from rich text element in Contentful?


I'm writing a Blazor site using Contentful as the CMS. I have 2 needs surrounding the Rich text Document type.

  1. I need to loop the entire Document body and isolate the Heading-2 portions and then render the values into a list

  2. I need to get the first Paragraph element in a document type and render the value of that.

I am using the following code: Case 1:

foreach (IContent node in ccContent.Items.bodyText.Content)
{
   switch (node)
   {
      case Heading2 h:
-------->   h.Content.Value can be seen in a breakpoint, but not 
-------->   available to render in code
        break;
      default:
        break;
   }
}

Case 2:

foreach (var article in articles)
{
    foreach (IContent node in article.response.Content)
    {
       switch (node)
       {
          case Paragraph p:
            IContent content = p.Content.FirstOrDefault();
-------->   content.Value can be seen in a breakpoint, but not 
-------->   available to render in code?
            break;
       }
    }
}

Solution

  • You need to type check and cast your IContent content to the correct type.

    For example:

    if(content is Text) {
       var v = (content as Text).Value;
    }