Convert plain text with html tags to html string and render it in Blazor
Asked Answered
F

3

5

Sample:

@{
     var s = "<p>Sample text</p>";
 }

Expectation:

Sample text.

I want it rendered on browser but I couldn't render it. It just outputs the whole value of s as text string. I already try

@(new HtmlString(s))

encoded it with HttpUtility.HtmlEncode and decode it with HttpUtility.HtmlDecode but still no use.

Fosse answered 11/2, 2020 at 10:52 Comment(0)
M
14

You will need

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

@code
{
    string s = "<p>Sample text</p>";
}

The <p> will render inside the <div>

Margo answered 11/2, 2020 at 11:57 Comment(2)
Google couldn't find that MarkupString keyword.Fosse
@user3856437: It is part of the Microsoft.AspNetCore.Components Namespace in ASP .NET Core.Jesusa
W
2

Using RenderFragment :

@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

@StringToHtml("Hello<h1>text</h1>")

@code {

    RenderFragment StringToHtml(string htmlString)
    {
        return new RenderFragment(b => b.AddMarkupContent(0, htmlString));
    }
}
Watermark answered 18/2, 2022 at 4:5 Comment(0)
N
0

Alternative markup (works in @code {...} as well)

@{
    // you can do this as well
    RenderFragment s = @<span>hello</span>;

    @s

    // or this
    @: this is a string as well, multiline not possible
    @: well kinda, but each new line needs "this" prefix then
    @: @s world.
}
Nerval answered 1/11 at 18:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.