59

I am attempting to render an address from my model. The string contains line breaks that I am replacing with a break tag. Although, it is rendering on the page as a string instead as HTML. How can I force my string to render as HTML instead?

Attempt:

<span id="addressLine">
    @Model.MyData.Address.Replace("\r\n", "<br />");
</span>

Result on page:

Address Top<br />Street Name<br />City<br />PostCode

Should be displayed as:

Address Top
Street Name
City
PostCode
Fizzix
  • 23,679
  • 38
  • 110
  • 176

5 Answers5

91

Use @Html.Raw(Model.MyData.Address.Replace("\r\n", "<br />"))

dom
  • 6,702
  • 3
  • 30
  • 35
  • 13
    Be careful using this, as if the user's address is `1234 lane`, you will have xss problems – John Koerner Dec 04 '14 at 01:48
  • @JohnKoerner - Don't worry, we clean out everything and format the address before saving it in the database. Thanks for the heads up though. – Fizzix Dec 04 '14 at 02:08
  • 1
    This is no longer the best answer. A couple of answers below use a CSS/HTML strategy that avoids the use of `Html.Raw`. The problem with line-breaks is a CSS/HTML one, and modern browsers can be controlled (with CSS/HTML) to behave how you intend. – Kind Contributor Aug 15 '19 at 13:38
31

Use

@(new HtmlString(@Model.MyData.Address))

It is safer, so that you avoid potential xss attacks

See this post: Rendering HTML as HTML in Razor

cnom
  • 3,071
  • 4
  • 30
  • 60
  • How does it avoid potential xss attacks? It is just a wrapper around a string to indicate that when used on a view that the content shouldn't be encoded, so any untrusted content will be displayed the same as Html.Raw. – Kelvin Jun 13 '21 at 21:36
9

Use css to preserve the white space

Html

<div id="addressLine">
  @Model.MyData.Address;
</div>

Css

#addressLine {
  white-space: pre;
}
  • This answer is also better because you no longer need to use `Html.Raw`. – Kind Contributor Aug 15 '19 at 13:36
  • This answer is only about css, not about html encoding or rendering html as is with razor. Which happens serverside, so little to do with css in this case. – Michael Oct 11 '21 at 08:37
7

To render HTML on blazor you can use MarkupString => @((MarkupString)here your string) this will render the string as HTML

<span id="addressLine">
    @((MarkupString)@Model.MyData.Address.Replace("\r\n", "<br />"));
</span>
Game dev
  • 296
  • 2
  • 17
1

You should use CSS whitespace property instead of it. For more details, access http://www.w3schools.com/cssref/pr_text_white-space.asp

It also helps you avoiding Cross-site scripting (http://en.wikipedia.org/wiki/Cross-site_scripting)

Thiago
  • 11
  • 1