¿Cómo crear un control TextBox derivado?

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;
            }
        }


    }
}

preguntado el 08 de noviembre de 11 a las 16:11

2 Respuestas

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:

http://www.4guysfromrolla.com/articles/100103-1.aspx

respondido 08 nov., 11:20

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

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.

Respondido el 20 de Septiembre de 14 a las 00:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.