Mykhailo Bykhovtsev
Mykhailo Bykhovtsev

Reputation: 512

Blazor using MarkupString for rendering HTML does not refresh it when value of string changed

So I am using this solution Example #2 on how to properly render HTML in Blazor while it is sanitized

Basically I am trying to make a box that switches between editing Standard Markdown to rendering it as HTML. I used Markdig package to convert Standard Markdown string to HTML.

But the trouble I have is that whenever renderedHTML is updated the MarkUpStringSanitizedComponent component remains the same. In fact it always remains the same as renderedHTML was initialized, it does not get updated. Maybe I did data binding wrong?

Here is how I use the component inside of editBox.razor

<div>
    @if (editMode)
    {
        ...
        input box version
        ...
    }
    else
    {
        <div class="editing-input inputs" @ondblclick="SwitchModes">
           <MarkupStringSanitizedComponent Content="@renderedText"/>
        </div>
    }
</div>
...

@code{

    public string renderedText {get; set;} = "<p class='markup'>This is a <em>markup string</em>.</p>";

    private bool editMode = false;

    private async Task SwitchModes(MouseEventArgs e)
    {
        editMode = !editMode;
        await MarkUpToHTML();
    }

    private async Task MarkUpToHTML()
    {
        var pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().Build();
        string renderedText = Markdown.ToHtml(Text, pipeline);
        Console.WriteLine("original text: \"" + Text + "\"");
        Console.WriteLine("rednered text: \"" + renderedText + "\"");
        await base.InvokeAsync(StateHasChanged);
    }
}

Upvotes: 1

Views: 3193

Answers (1)

Vi100
Vi100

Reputation: 4203

Your code has a simple fail:

In the MarkUpToHTML method you are generating the rendered output but you aren't assigning it to renderedText global variable, instead you have redeclared it on the method's scope, so it's value never goes where you want...

So, simply change:

string renderedText = Markdown.ToHtml(Text, pipeline);

for:

renderedText = Markdown.ToHtml(Text, pipeline);

and give it a try. Good luck!

Upvotes: 3

Related Questions