Todd
Todd

Reputation: 550

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?

Upvotes: 3

Views: 187

Answers (2)

Brian Parker
Brian Parker

Reputation: 14593

Use MarkupString

@((MarkupString)link)

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

Upvotes: 4

Rikudou En Sof
Rikudou En Sof

Reputation: 758

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

Upvotes: 1

Related Questions