"<" in a text box in ASP.NET --> how to allow it?
I have a textfield which displays a string which contains < and >. The code throws an error because of that. How can I allow the usage of those chars in my textfield?
Thanks :)
Solution 1:
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.
Solution 2:
If you're in an asp.net page, you can wrap the whole of the output text in a
Server.HtmlEncode("YourTextWith<and>Characters")
function and it will encode any dodgy characters for you.
If, for some reason, you're doing this in a .cs file, you can use System.Web.HttpUtility.HtmlEncode("YourTextWith<and>Characters")
before passing it to the presentation layer.