1

I display some content in my view using this: <%= Html.Encode(Model.synopsis) %>

The content synopsis has the HTML characters escaped so for example some content stored in the database like this would look like:

&lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit
anim id est laborum.&lt;/p&gt;

How would I change my code to show it as HTML? So the escaped HTML becomes HTML on the front end.

Thanks.

1
  • Since you have HTML encoded HTML in the database, you need to decode it before showing it. But it would be alot easier to not have HTML encoded HTML in the database. :) ("HTML encoded" means "encoded to be included in HTML" - no need to do that when storing it in a database.) Commented Mar 29, 2011 at 19:29

2 Answers 2

7

Don't use Html.Encode. Just do

<%= Model.synopsis %>

Html.Encode encodes any special html characters and escapes them. You may want to be careful and make sure you're not opening yourself up for XSS by allowing users to enter any markup that will be executed by the browser.

Also for the times you want to encode your output, you can just use the <%: tag

<%: Model.synopsis %>

is equivalent to

<%= Html.Encode(Model.synopsis) %>
Sign up to request clarification or add additional context in comments.

3 Comments

That reverses it though so now I see the code instead of it being made into actual HTML!
@cameron, I'm confused then, what is it that you're trying to achieve?
What you see above in OP is what is stored in my database. When I show it in the view it shows it like &lt;p&gt;some text...&lt;/p&gt; but when removing the encode it shows it like <p>text...</p> so it's not converting my escaped HTML into HTML when viewed.
4

Does <%= Html.HtmlDecode(Model.synopsis) %> do the trick in your case?

Here is the reference to the actual function in MSDN - http://msdn.microsoft.com/en-us/library/hwzhtkke.aspx

1 Comment

In that case try doing Server.HTMLDecode. P.S. I also edit the method name in the answer as I had a typo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.