How to Inject HTML in a Blazor Component

This past weekend, while working on a new Blazor application, I ran across a need to inject HTML code in a Blazor component. Originally, I went down the RenderFragment path. However, there’s a much simpler and more elegant solution. What we’re going to build is a Blazor component that allows us to inject HTML code. The HTML code we’re going to inject is an iFrame that will play a video from Twitch.tv.

Let’s get to work!

Create a new Blazor WebAssembly project and name it whatever you wish:

You can delete all the razor pages under Pages, except for Index.razor. From the Shared directory, remove the NavMenu.razor, NavMenu.razor.css, and SurveyPrompt.razor. Inside MainLayout.razor, remove the div that references NavMenu. In Pages/Index.razor, remove the reference to SurveyPrompt.razor.

Your project should now look like this:

Let’s now create a new Razor component:

I prefer code behind instead of C# code inside my razor. So, I refactor to move the code. This is purely a personal preference:

I also like to remove unused using statements:

In Html.razor, paste the following code:

<div>
    @((MarkupString) ChildContent)
</div>

In Html.razor.cs, declare a public string property ChildContent parameter:

[Parameter]
public string ChildContent { get; set; }

Please notice that the ChildContent is defined as a string, not a RenderFragment! Now, let’s add the new component to the Index.razor:

 <div>
    <Html ChildContent="@Html"></Html>
</div>

Here’s the code to add to Index.razor.cs:

namespace BlazorHTMLInjection.Pages
{
    public partial class Index
    {
        string Html = null;

        protected override Task OnInitializedAsync()
        {
            Html = $@"<iframe width=""1024px"" height=""768px"" src=""https://player.twitch.tv/?video=v1545363965&parent=localhost"" allowfullscreen></iframe>";
            return base.OnInitializedAsync();
        }
    }
}

Build and run the project. The video should be loaded in the window:

Warning:

By using MarkupString, you are responsible to validate the encoded HTML to prevent Cross Site Scripting.

That’s how it’s done. Happy coding!

About the Author

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You may also like these