Home > Blockchain >  MarkupString does not work as expected with String.Format in Blazor
MarkupString does not work as expected with String.Format in Blazor

Time:02-04

I am trying to use to apply string format to a string coming from a resource file.

<p >@((MarkupString)(String.Format(Localizer["Test"], 2)))</p>

But this is how it is displayed in the browser:

You have done <span > 2 </span> tests.

What should I do for it to take the proper styling?

I've tried this solution but it says:

The type or namespace name 'HtmlSanitizer' could not be found 

I am using Blazor server with .NET6

EDIT: I have a file called App.resx

<data name="Test" xml:space="preserve">
    <value>
      You have done 
      &amp;lt;span &amp;gt; 
        {0}
      &amp;lt;/span&amp;gt;
      tests.
    </value>   
</data>

CodePudding user response:

You have double encoded the resource string, change it to You have done &lt;span &gt; {0} &lt;/span&gt; tests:

<data name="Test" xml:space="preserve">
  <value>You have done &lt;span &gt; {0} &lt;/span&gt; tests</value>
</data>

So Localizer["Test"] returns You have done <span > {0} </span> tests.

Note that if you are using resource editor you can just add the string as is and it will encode it correctly so it can be stored in the xml.

  • Related