How can I make HTML elements stored as C# strings display properly?

I have some HTML code that is stored in a C# string. I would like it to display as text rather than HTML code. Here is some sample code:

@page "/page"
@using System
@using System.Net

@{
    var link = "<a href='https://apple.com'>Link</a>"
}

<h1>Page</h1>

@WebUtility.HtmlDecode(link)

I am using Blazor (not MVC) and I have tried using the HtmlDecode method as recommended in this question. I would like the link to display as such:

link

but it displays as:

<a href="https://apple.com">link</a>

I am having the same problem with other HTML elements too. Does anyone know how I can make it display correctly?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Use MarkupString

@((MarkupString)link)

@{
    string link = "<a href='https://apple.com'>Link</a>"
}

Method 2

If you have saved an Html. Then try using @variableName, instead of using HTML helpers or Razor helpers

@page "/page"
@using System
@using System.Net

@{
    var link = "<a href='https://apple.com'>Link</a>"
}

<h1>Page</h1>

@link


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x