1

I need to create a custom TextBox control that allows user input HTML tags. I added a new property called HtmlEnabled, default is false. If it is false, it will act exactly like the original TextBox; if it is set to true, it will call Server.HtmlEncode to encode the text. I never creat a custom control, can anyone tell me what do I need to do? What function I need to override? Thanks.

I created my TextBoxEx class as following: I still get the validation error when I set HtmlEnabled to true, can anybody tell me what is wrong?

namespace WebApplication1
{
    [ToolboxData("<{0}:TextBoxEx runat=server></{0}:TextBoxEx")]
    public class TextBoxEx : System.Web.UI.WebControls.TextBox
    {
        public bool HtmlEnabled
        {
            get
            {
                return (bool)ViewState["HtmlEnabled"];
            }
            set
            {
                ViewState["HtmlEnabled"] = value;
            }
        }

        public TextBoxEx()
        {
            ViewState["HtmlEnabled"] = false;
        }

        public override string Text
        {
            get
            {
                if (HtmlEnabled)
                    return HttpUtility.HtmlEncode(base.Text);
                else return base.Text;
            }

            set
            {
                if (HtmlEnabled)
                    base.Text = HttpUtility.HtmlDecode(value);
                else base.Text = value;
            }
        }


    }
}
1

2 Answers 2

0

Sounds like you could just inherit from the TextBox control and override the Text property. This article should get you started on how to go about doing it:

https://web.archive.org/web/20211020203142/https://www.4guysfromrolla.com/articles/100103-1.aspx

1
  • 1
    This is what I have tried. But I still got the validation error when I set HtmlEnabled to true. Do u know what I did is wrong?
    – GLP
    Nov 8, 2011 at 18:55
0

In order to allow the page to accept HTML tags, you need to disable request validation.

<%@ Page Language="C#" ValidateRequest="false" AutoEventWireup="true" CodeBehind="TestPage.aspx.cs" Inherits="MyNamespace.TestPage" %>

This has nothing to do with the textbox control, the request validation checks all page input (query string parameters, cookies, headers, and form fields) to ensure that there are no potentially malicious scripts in the request. Be aware that by turning it off, you will need to validate that the input isn't harmful yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.