HTMLencode HTMLdecode

I have a text area and I want to save the text entered by the user in the database with html formatting, for example, with a paragraph, a numbered list. I use HTMLencode and HTMLdecode for this.

An example of my code looks like this:

string str1 = Server.HtmlEncode(TextBox1.Text); Response.Write(Server.HtmlDecode(str1)); 

If the user enters text with two paragraphs, str1 displays the characters \ r \ n \ r \ n between paragraphs. but when he writes it to the screen, just add the second paragraph from the 1st. Although I’m deciphering it, why doesn’t it print 2 paragraphs?

+4
source share
3 answers

A simple solution:

 string str1 = Server.HtmlEncode(TextBox1.Text).Replace("\r\n", "<br />"); 

This assumes that you only care about getting the correct tags <br /> . If you need a real formatter, you will need a library, for example, proposed by Aaronaught.

+12
source

This is not what HtmlEncode and HtmlDecode . Even close.

These methods are designed to "shield" HTML. < becomes &lt; , > becomes &gt; etc. You use them to avoid user input, to avoid cross-site scripting attacks and related problems.

If you want to be able to enter text input and convert it to HTML, consider a formatting tool like Markdown (I believe that Qaru uses MarkdownSharp ).

If all you need is line breaks, you can use text.Replace("\r\n", "<br/>") , but working with more complex structures such as ordered lists is difficult, and there are already existing tools for processing it.

+2
source

HTML does not recognize \ r \ n as line breaks. Convert them to p or br tags.

0
source

All Articles