How do I display user input text in a way that treats it like plain text even if it's got html tags?
i have a label inside my page which displays data entered by the user.
The problem is if the user enters somet开发者_开发技巧hing like
"Hey Jim, thought about using the <a> tag"
i have a label inside my page which displays data entered by the user.
I have used Uri.EscapeDataString and Uri.UnescapeDataString to encode and decode the data so it can be safely stored in database.
The <a>
will be intrepreted as HTML and will do weird things to the rest of the label.
How can I get it to display <a>
just like a normal plain text, instead of as a HTML label.
Use Server.HtmlEncode() like so:
lbl.Text = Server.HtmlEncode("Today is the Greatest! <b>Hi!</b>");
There's a little more to this than the other answerers have caught. In order to allow the user even to enter the angle brackets, you have to turn off ValidateRequest for the page in question. Otherwise, you'll get an exception.
When you do so, you need to be vigilant to prevent cross-site scripting and other attacks. There is an overview on MSDN.
Basically, though, you do need to use entities, as other posters have suggested, to change the angle brackets into something "safe."
Use entities to represent characters that have special meaning in HTML
精彩评论