Problem is that when this gets posted to server, it will not work, doesn’t matter what you try. This is the ASP.NET XSS protection, which can be disabled like so:

<%@ Page ... ValidateRequest="false" %>

Trouble is, you’ll have to be very careful validating all the postback yourself. Easier way is to escape all the contents of textbox using javascript just before posting. You can escape it using same HTML escaping, then unescape in server side code.

Update:
Example of escaping. This will flash the changed text on screen before postback – ideal solution is to use a hidden field for this, i.e. assign value to a hidden field, instead of that same field. This is the simplest version:

<script>
  function EscapeField(){
    document.getElementById("your client control ID").value = 
       escape(document.getElementById("your client control ID").value);
  }
</script>

And in code-behind:

this.ClientScript.RegisterOnSubmitStatement(this.GetType(), 
    "EscapeField", "EscapeField();")

Update:
Again, warning – if you save HTML in your database like this, and then just display it to the client, you are directly vulnerable to XSS attacks. There are worms out there that will find and exploit your web site. Make sure you cleanse the HTML you are getting.

Leave a Comment