Fizzix
Fizzix

Reputation: 24395

Render a string as HTML in C# Razor

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

Upvotes: 65

Views: 82724

Answers (5)

Game dev
Game dev

Reputation: 324

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>

Upvotes: 10

cnom
cnom

Reputation: 3241

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

Upvotes: 34

user3559349
user3559349

Reputation:

Use css to preserve the white space

Html

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

Css

#addressLine {
  white-space: pre;
}

Upvotes: 10

Thiago
Thiago

Reputation: 11

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)

Upvotes: 1

dom
dom

Reputation: 6842

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

Upvotes: 100

Related Questions