Dave
Dave

Reputation: 4028

Is there an equivalent to Html.Raw in Blazor?

I have some HTML that is stored in a string. How can I render it in a Blazor/Razor view without automatic HTML encoding?

Upvotes: 152

Views: 84702

Answers (6)

Vaibhav Pathade
Vaibhav Pathade

Reputation: 131

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

@code {
    string InputString = "html code";
}

Upvotes: 9

Flores
Flores

Reputation: 8932

Not right now, but will have it probably in the next version: Follow this.

Workaround (from that issue):

cshtml

<span ref="Span"></span>

@functions{
    [Parameter] string Content { get; set; }
    private ElementRef Span;

    protected override void OnAfterRender()
    {
        Microsoft.AspNetCore.Blazor.Browser.Interop.RegisteredFunction.Invoke<bool>("RawHtml", Span, Content);
    }
}

index.html

<script>
    Blazor.registerFunction('RawHtml', function (element, value) {
        element.innerHTML = value;
        for (var i = element.childNodes.length - 1; i >= 0; i--) {
            var childNode = element.childNodes[i];
            element.parentNode.insertBefore(childNode, element);
        }
        element.parentNode.removeChild(element);
        return true;
    });
</script>

Upvotes: 4

Ibrahim Timimi
Ibrahim Timimi

Reputation: 3700

You can also store the raw HTML as string to a variable of type MarkupString, then you can use it without casting.

@myMarkup

@code {
    private MarkupString myMarkup = 
        new MarkupString("<p class='markup'>This is a <em>markup string</em>.</p>");
}

output

Upvotes: 12

Mirko MyRent
Mirko MyRent

Reputation: 211

<span class="link-dark">@((MarkupString)(get_user(user_row["user_name"].ToString())))</span>

Upvotes: 1

Alan1963
Alan1963

Reputation: 209

Yes, sample:

@page "/"

<h2>Title</h2>
<hr />
<p>
    @ms
</p>
@code {
    MarkupString ms => (MarkupString)description;

    string description = $@"
This is an example of how Azure serverless functions can be consumed from Blazor WASM.
<br><br>
To run this project in development mode, the <b>HttpTriggerSample</b> project must be run simultaneously.
<br><br>
Serverless Functions origin: <b>{fs}<b>.";

    // by example
    static string fs => Program.IS_DEVELOPMENT ? "DevelopmentStorage" : "Azure";
}

Upvotes: 17

Maxim Kornilov
Maxim Kornilov

Reputation: 6055

Feature to render raw HTML was added in Blazor 0.5.0 version. This is the example of how raw HTML can be rendered from string containing HTML content:

@((MarkupString)myMarkup)

@functions {
    string myMarkup = "<p class='markup'>This is a <em>markup string</em>.</p>";
}

More info can be found in "Blazor 0.5.0 experimental release now available" announcement.

Upvotes: 271

Related Questions