Search code examples
htmlblazorrichtext

Display text in Blazor with rich text


I am using Blazor with a rich text editor. When I output text like this:

enter image description here

It adds quotes around the text and the actual markup is displayed:

enter image description here

My markup is displayed with quotes, and the actual markup (bold and color) is not displayed. Does anyone know why or how to make this work with Blazor?


Solution

  • The issue is fundamental to the way Blazor compiles and renders pages. The components are built as generated classes during compilation that then use a RenderTreeBuilder to generate the HTML back out again. This in turn takes your inputs to be string literals and outputs them as such, as what blazor is seeing in your markup is "insert string x into position y", not actual HTML markup.

    EDIT I found a simple way to do this shortly after I answered so I placed it here, using the type MarkupString. Setup is done like this:

    MarkupRenderer.razor

    @((MarkupString)Markup)
    
    @code {
    
        [Parameter]
        public string Markup { get; set; }
    
    }
    

    and then in your parent you use it like so:

    Parent.razor*

    
    .....
    
    <MarkupRenderer Markup="@markupString" />
    
    

    This will render out the tags and attributes as you are looking for to get the content output as HTML.

    Official documentation on this is very short and includes the warning: "Rendering raw HTML constructed from any untrusted source is a security risk and should be avoided!", which it is, so keep that in mind if you haven't already.