8

Is there a way to pass a string with HTML tags without changing the Razor code?

Scenario (current code):

string msg = "<a href='http://www.google.com/html/'>Google</a>";

OUTPUT:

<a href='http://www.google.com/html/'>Google</a> on the page.

GOAL result:

Link to Google without changing the code "@msg".

3
  • 2
    try @Html.Raw(HttpUtility.HtmlDecode(msg)); Commented Aug 11, 2015 at 18:20
  • That's changing the Razor code though but thanks. Commented Aug 11, 2015 at 18:21
  • 1
    @Amogh: There's no need to decode first. In fact, unless, you know you're dealing with an encoded HTML string, this is likely to result in invalid HTML, as things like &amp;, which should be output exactly as is to the page, will end up as & which is invalid. Commented Aug 11, 2015 at 18:25

4 Answers 4

18

try @Html.Raw(HttpUtility.HtmlDecode(msg));

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

Comments

4

You can try with

HtmlString msg = new HtmlString("<a href='http://www.google.com/html/'>Google</a>");

instead of

string msg = "<a href='http://www.google.com/html/'>Google</a>";

3 Comments

I apologized, I need to clarify further. Since I cannot change and Razor code, is there a way to construct the content of the string so that it converts its content into HTML tags/elements.
You can use HtmlString in the controller, so you don't touch the razor code.
Sorry this should be last add for me - no code change besides string "msg" content. No Razor or any .NET/MVC code changes. The string value is retrieved from external source (database).
4

Hey You can edit your razor code as:

@{

     HtmlString msg = new HtmlString("Hello <br> Hello Again");
     <p style="text-align:justify;"> @msg  </p>
 } 

It's simple

Comments

0

I will put this here just in case it saves time someone i the future - using Html.Raw did not seem to help in a razor component on .Net 8 . Using conversion to MarkupString did solve the issue

<p>Your text msg: @((MarkupString) msg) </p>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.