views:

322

answers:

3

I have a text area and I want to store the text entered by user in database with html formatting like paragraph break, numbered list. I am using HTMLencode and HTMLdecode for this.

Sample of my code is like this:

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

If user entered text with 2 paragraphs, str1 shows characters \r\n\r\n between paragraphs. but when it writes it to screen, just append 2nd paragraph with 1st. While I'm decoding it, why doesn't it print 2 paragraphs?

A: 

HTML doesn't recognize \r\n as a line break. Convert them to "p" or "br" tags.

jvenema
A: 

That's not what HtmlEncode and HtmlDecode do. Not even close.

Those methods are for "escaping" HTML. < becomes &lt;, > becomes &lt;, and so on. You use these to escape user input in order to avoid Cross-Site Scripting attacks and related issues.

If you want to be able to take plain-text input and transform it into HTML, consider a formatting tool like Markdown (I believe that Stack Overflow uses MarkdownSharp).

If all you want are line breaks, you can use text.Replace("\r\n", "<br/>"), but handling more complex structures like ordered lists is difficult, and there are already existing tools to handle it.

Aaronaught
I want to format all kind of HTML input in text area like line break, numbered list etc whatever user enters just like if I'm writting right now in text area(on stack overflow) and it will printed on screen as I'm entering. Aaronaught suggested that I can use Markdown. But Is there any inbuilt function in .net framework by which I can achieve this functionality? Thanks to all who replied this question.
elenor
@elenor: No, this type of thing is definitely not built into the .NET Framework. That's why projects like MarkdownSharp exist.
Aaronaught
thanks Aaronaught
elenor
A: 

The simple solution would be to do:

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

This is assuming that you only care about getting the right <br /> tags in place. If you want a real formatter you will need a library like Aaronaught suggested.

Kelsey