Encode HTML - Have validateRequest = True

A co-worker and I had a situation today in which we wanted a particular TextBox control to allow HTML. The only problem, is that validateRequest must be done across the entire website, or for the particular page. Because of these restrictions, and the fact that the UserControl being built is placed in a dynamic page for a portal, we had to research ways to allow HTML posted entries but still keep validateRequest=True.

After doing a little bit of research, I came across the idea of replacing the character representation of common HTML elements via Javascript then decoding that information with Server.HtmlDecode.

The code is as follows:

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="Test.WebForm1"
validateRequest="true"%>
<html>
   <body>
      <form runat="server">
         <script language="javascript">
            function encodeMyHtml(toEncode) {
               return toEncode.replace(/&/gi, '&amp;').replace(/\"/gi, '&quot;').replace(/</gi, '&lt;').replace(/>/gi, '&gt;');

            }
         </script>

         <asp:TextBox Runat="server" ID="tbEncodedText" TextMode="MultiLine" Columns="100" Rows="10" >
         <asp:Button Runat="server" ID="btnSubmit" Text="Submit My HTML" OnClick="btnSubmit_Click"/>
         <hr>
         <asp:Literal Runat="server" ID="outputHTML" />
      </form>
   </body>
</html>
Then in my code-behind I have this in my Page_Load function to add the onclick attribute:
private void Page_Load(object sender, System.EventArgs e)
{
   if(!Page.IsPostBack)
   {
      btnSubmit.Attributes.Add("onclick", "this.form." + tbEncodedText.ClientID + ".value = encodeMyHtml(this.form." + tbEncodedText.ClientID + ".value);");
   }

}
Then my button event, I have:
private void btnSubmit_Click(object sender, EventArgs e)
{
   outputHTML.Text = Server.HtmlDecode(tbEncodedText.Text);
   tbEncodedText.Text = Server.HtmlDecode(tbEncodedText.Text);
}


Overall, this provides a nice solution to not having your entire web application or page allow HTML elements.

[Previously Posted on old Weblog on July 17, 2003]

2 Comments

  • Good idea! I've been facing the same problem, though I had not yet spent the time to think a way around it. Now I don't have to! :)



    Joe

  • Hi,



    When I attempt to insert this javascript code into my HTML code, the &quot; (quote) in the replace string function prevents the &lt;/script&gt; tag from closing. What am I missing? Thanks.



    Richard

Comments have been disabled for this content.