Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 502
Fizzix Avatar asked Dec 04 '14 01:12

Fizzix


People also ask

How do I render a string in HTML?

To render the html string in react, we can use the dangerouslySetInnerHTML attribute which is a react version of dom innerHTML property. The term dangerously is used here to notify you that it will be vulnerable to cross-site scripting attacks (XSS).

What method is used to render HTML string in a view?

You can use the Html. Raw() method for that.

What is HTMLString?

Unlike most HTML parsers which generate tree structures, HTMLString generates a string of characters each with its own set of tags. This flat structure makes it easy to manipulate ranges (for example - text selected by a user) as each character is independent and doesn't rely on a hierarchical tag structure.

How render content HTML react?

React renders HTML to the web page by using a function called ReactDOM. render() .


2 Answers

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

like image 63
dom Avatar answered Oct 06 '22 05:10

dom


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

like image 35
cnom Avatar answered Oct 06 '22 06:10

cnom