Reputation: 12716
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>
<p>Testing HTML</p><p>Hope it works</p>
</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.
Upvotes: 2
Views: 4692
Reputation: 26494
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.
Upvotes: 2
Reputation: 20674
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());
}
}
Upvotes: 0