Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I render html in a field in Blazor

I have a field saved in the DB with HTML. I am using TinyMCE for my text editor and it is correctly saving the HTML tags in the DB. However, when I render the field, it still shows the tags. Initaily I had this:

<td>
    @objInv.Notes
</td>

My latest attempt to resolve this is:

<td>
    @(new HtmlString(objInv.Notes))
</td>

Either way, it still renders as:

<p>New laptops 09/07/2022 <strong>test</strong></p>

What I desire is:

New laptops 09/07/2022 test

like image 324
Steve Cross Avatar asked Oct 27 '25 05:10

Steve Cross


1 Answers

In Blazor, rendering raw HTML is achieved using the MarkupString class. For instance, you can assign your raw HTML to a string variable and then cast it as a MarkupString when rendering. Alternatively, you can directly declare and initialize a MarkupString field.

Here's an example:

@tableTitle

<table class="table table-striped">
    <thead>
        <tr>
            <th>Notes</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>@((MarkupString)myNote)</td>
        </tr>
    </tbody>
</table>

@code {
    string myNote = "<p>New laptops 09/07/2022 <strong>test</strong></p>";
    MarkupString tableTitle = new MarkupString("<h1 style='color: blue;'>Laptop Notes</h1>");
}

Output:

Raw HTML rendering in Blazor

like image 135
Ibrahim Timimi Avatar answered Oct 28 '25 18:10

Ibrahim Timimi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!