Skip to content

How To Safely Display Data From ASP.NET TextField Inputs

Updated: at 11:18 PM

Let’s say you have a user input field that you want the user to type data into which will be later displayed back to the user.  You don’t want the user putting in their own html or other things (like javascript tags) because that could cause bad things to happen on your page. 

The easiest thing to do is to set the page attribute to not do request validation

<%@ Page Title="" Language="C#" MasterPageFile="~/DefaultNoColumns.master" AutoEventWireup="true" ValidateRequest="false"
CodeFile="SponsorInformationEdit.aspx.cs" Inherits="SponsorInformationEdit" %>

Then, store whatever the user types in the textbox including the nasty things like <script …

When you get around to displaying the data back, simply encode it like this:

LabelShortDescription.Text = HttpUtility.HtmlEncode(rec.CompanyDescriptionShort);

Then, if the user put a bold tag in the html, they will get this displayed back:



and no harm will occur.