0

I'm using Blazor for a documentation project where I need to post code samples for other devs. This article suggested using MarkupString as the solution to print the raw code without rendering it.

My razor.cs page looks like this:

public partial class Sample { public string Html { get; set; } = "<div class=\"top-row px-4\" style=\"padding-top:0px\">"; public MarkupString Markup { get; set; } protected override void OnInitialized() { base.OnInitialized(); Markup = new MarkupString(Html); } } 

And the .razor page looks like this:

 Code sample goes here: <pre> <code> @Markup </code> </pre> @Markup 

When I run the server, both @Markup instances are being rendered by the browser rather than printing the raw HTML like I'd hoped to see:

<div style="height: 100%;"><!--!--> Markup here <pre><code><!--!--><div class="top-row px-4" style="padding-top:0px"></div></code></pre><!--!--> <!--!--><div class="top-row px-4" style="padding-top:0px"></div></div> 

enter image description here

How can I make the blazor page print Markup as text without interpreting it?

1
  • Replace @Markup with @Html . Markup = new MarkupString(Html); is doing the opposite of what you want. Commented Aug 26, 2022 at 6:13

1 Answer 1

2

create MarkupComponent.razor as

@Markup @code{ private string Markup; [Parameter] public string Text { get; set; } protected override void OnParametersSet() { Markup = new MarkupString(Text).Value.ToString(); } } 

and use

 <MarkupComponent Text="@Html" /> @code { string Html = "<div class=\"top-row px-4\" style=\"padding-top:0px\">"; } 

and the result is: enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

MarkupString.Value is the same as the original Text, and it is already a string. So the short form of Markup = new MarkupString(Text).Value.ToString(); is just Markup = Text;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.