Mark
Mark

Reputation: 2760

How to display a text (Html format) in a website (Asp.net C#)

I have a text editer, after applying format to the text I display the text when a button is clicked. I want the text to be displayed with all the formatting applied in the text editor.

 lbl_Subject.Text = Server.HtmlEncode(formattedtext);

but it is not displayed in the format applied instead it is displayed as

<p> This is Para 1</p> <p> this is Para 2</p> <p> <strong>this is bold</strong></p>

how can I display the text with all the format applied in text editor

Update i tried with literal

the result is

&lt;p&gt; This is Para 1&lt;/p&gt; &lt;p&gt; this is Para 2&lt;/p&gt; &lt;p&gt; &lt;strong&gt;this is bold&lt;/strong&gt;&lt;/p&gt;

Upvotes: 6

Views: 41935

Answers (7)

Mukus
Mukus

Reputation: 5033

Another way to do this is by adding the pre tags. This will look like,

 lbl_Subject.Text = $"<pre>{formattedtext}</pre>"

If the label does not work change that to a div.

div_Subject.InnerHtml =  $"<pre>{formattedtext}</pre>"

Upvotes: 0

mehdi gh
mehdi gh

Reputation: 1

You can use this code : Html.Raw(formattedtext)

Upvotes: 0

Chamika Sandamal
Chamika Sandamal

Reputation: 24302

use div instead of label.

div1.InnerHtml=formattedtext;

Upvotes: 8

Robert Giesecke
Robert Giesecke

Reputation: 4314

Take a look at the AntiXssLibrary (can be found via nuget).

Especially at the Sanitizer class. It takes a string and removes every security-related stuff from it.

it will change the names of css classes as well, so you might have to tinker with the results, to restore the class names. But it definitely allows you to get RAW HTML safely on your page, w/o risking XSS attacks.

Upvotes: 0

Joel Etherton
Joel Etherton

Reputation: 37533

If you want the text to render as html in the browser, then why are you HtmlEncoding it? HtmlEncode is intended to take code that potentially has html symbols in it and encode it so that those symbols print as raw text. I would say the code you presented behaves exactly as it should be expected to behave. If you want your code to output html to be rendered, then it should be with a literal and it should simply be text.

lit_Subject.Text = formattedtext;

Upvotes: 2

Louis Waweru
Louis Waweru

Reputation: 3672

HtmlEncode makes sure that text is displayed correctly in the browser and not interpreted by the browser as HTML.

Try removing HtmlEncode or using HtmlDecode.

Upvotes: 6

ZombieSheep
ZombieSheep

Reputation: 29953

You may want to use a Literal Control instead of a label. This should take your raw HTML string and output it as required on the page.

ASIDE : Be very, very careful when displaying HTML like this. It is not difficult to add malicious scripts, for example, which will be run from the viewed page.

Upvotes: 1

Related Questions