views:

41

answers:

2

I want to allow HTML in a comment box (eventually use tinymce or something like that), store it in an MSSQL database, and then read it back to a page where the field is rendered in a tabl cell.

It all works fine with the storing of the HTML after I fixed the validation problem on the action method. But when read back from the database, it renders the text with the HTML tags visible, instead of formatted HTML. I.e. if I look at the HTML source code in the table, its like this:

        <td> 
            &lt;p&gt;Testing HTML&lt;/p&gt;&lt;p&gt;Hope it works&lt;/p&gt;
        </td> 

So how do I render it as formatted text? When I did this to test out the validation, I just wrote in the tags in the textarea.

A: 

You want to HtmlDecode

To give the MSDN example

HttpUtility.HtmlDecode Method

using System;
using System.Web;
using System.IO;

   class MyNewClass
   {
      public static void Main()
      {
         String myString;
         Console.WriteLine("Enter a string having '&' or '\"'  in it: ");
         myString=Console.ReadLine();
         String myEncodedString;
         // Encode the string.
         myEncodedString = HttpUtility.HtmlEncode(myString);
         Console.WriteLine("HTML Encoded string is "+myEncodedString);
         StringWriter myWriter = new StringWriter();
         // Decode the encoded string.
         HttpUtility.HtmlDecode(myEncodedString, myWriter);
         Console.Write("Decoded string of the above encoded string is "+
                        myWriter.ToString());
      }
   }
dove
Well, I already tried that, but it didn't work. But maybe I found the answer: I had used <%: item.Comment %> to write out the text in the view. I guess that : encodes it back, even though I used HtmlUtility.HtmlDecode in the controller. So if I changed to <%= item.Comment %> it seems to work.
Anders Svensson
A: 

Professional ASP.NET MVC provides this explanation about the differences in "code nuggets":

When we look at the Details.aspx template more closely, we’ll find that it contains static HTML as well as embedded rendering code. <% %> code nuggets execute code when the View template renders, and <%: %> code nuggets execute the code contained within them and then render the result to the output stream of the template.

Left out of this description is how a code nugget in a <%= %> works. Scott Guthrie describes the difference in his post New <%: %> Syntax for HTML Encoding Output in ASP.NET 4 (and ASP.NET MVC 2). Phil Haack discusses this in more detail in a series on HTML encoding blocks which starts with Html Encoding Code Blocks With ASP.NET 4.

What you've discovered is that <%= %> spits out raw HTML into the output stream while <%: %> does HTML encoding.

ahsteele
Thanks for the links!
Anders Svensson