Is there an equivalent to Html.Raw in Blazor?

后端 未结 2 815
梦毁少年i
梦毁少年i 2020-12-29 01:11

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

相关标签:
2条回答
  • 2020-12-29 01:24

    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.

    0 讨论(0)
  • 2020-12-29 01:27

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

    Workaround (from that issue):

    cshtml

    <pre>
        <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);
            }
        }
    </pre>
    

    index.html

    <pre>
        <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>
    </pre>
    
    0 讨论(0)
提交回复
热议问题