Adding an asynchronous callback to validate data (C#) : Validation « Custom Controls « ASP.NET Tutorial






using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebControlLibrary1
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")]
    public class WebCustomControl1 : WebControl, ICallbackEventHandler
    {
        private string text;

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Themeable(false)]
        public string Text
        {
            get
            {
                return text;
            }
            set
            {
                text = value;
            }
        }

        protected override void Render(HtmlTextWriter output)
        {
            output.RenderBeginTag(HtmlTextWriterTag.Div);

            output.AddAttribute(HtmlTextWriterAttribute.Type, "text");
            output.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID);
            output.AddAttribute(HtmlTextWriterAttribute.Name, this.ClientID);
            output.AddAttribute(HtmlTextWriterAttribute.Value, this.Text);

            output.AddAttribute("OnBlur", "ClientCallback();");        
            this.AddAttributesToRender(output);

            output.RenderBeginTag(HtmlTextWriterTag.Input);
            output.RenderEndTag();

            output.RenderEndTag();
        }

        protected override void OnPreRender(EventArgs e)
        {
            Page.ClientScript.RegisterStartupScript(
                typeof(Page),
                "ControlFocus", "document.getElementById('" + this.ClientID + "').focus();",
                true);

            Page.ClientScript.RegisterStartupScript(
                typeof(Page), "ClientCallback",
                "function ClientCallback() {" +
                    "args=document.getElementById('" + this.ClientID + "').value;" +
                    Page.ClientScript.GetCallbackEventReference(this, "args",
                        "CallbackHandler", null, "ErrorHandler", true) + "}",
                true);
        }

        #region ICallbackEventHandler Members

        public void RaiseCallbackEvent(string eventArgument)
        {
            int result;
            if (!Int32.TryParse(eventArgument, out result))
                throw new Exception("The method or operation is not implemented.");
        }

        public string GetCallbackResult()
        {
            return "Valid Data";
        }

        #endregion



    }
}








14.18.Validation
14.18.1.Adding an asynchronous callback to validate data (C#)
14.18.2.Adding an asynchronous callback to validate data (VB)