Reputation: 24395
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
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
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
Reputation:
Use css to preserve the white space
Html
<div id="addressLine">
@Model.MyData.Address;
</div>
Css
#addressLine {
white-space: pre;
}
Upvotes: 10
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