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

7

6

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;
Granddad answered 14/12, 2011 at 11:14 Comment(0)
S
8

use div instead of label.

div1.InnerHtml=formattedtext;
Sanasanabria answered 14/12, 2011 at 11:17 Comment(0)
S
6

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.

Superordinate answered 14/12, 2011 at 11:18 Comment(1)
Server.HtmlDecode(Server.HtmlEncode(formattedtext)) seems a little silly, but maybe that's just me.Dialectician
D
2

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;
Dialectician answered 14/12, 2011 at 11:26 Comment(0)
M
1

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.

Miniver answered 14/12, 2011 at 11:15 Comment(0)
P
0

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.

Pedagogue answered 14/12, 2011 at 11:27 Comment(0)
C
0

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

Children answered 31/8, 2014 at 7:27 Comment(0)
C
0

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>"
Chroma answered 13/1, 2020 at 3:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.