Search code examples
asp.netvisual-studio-2010ajaxcontroltoolkitasp.net-4.0

ASP.net Server Controls and using AjaxcontrolToolkit


I have a question about server controls VS. user controls (.ascx). Currently, when I write a user control, I want to be able to take advantage of using the AjaxControlToolKit DLL. In particular, I want my user control to be able to do partial post backs and use the various extenders (modalPopUp for example). My boss, though, prefers us to use server controls so that we can compile them into a DLL and use them in various applications. My question is: If I rewrite my user controls to be server controls, will I still be able to use the AjaxControlToolKit and all its features (asyn post backs and extenders)?

FYI: I am using Visual Studio 2010, AjaxControlToolkit 4.1.60919 and .Net 4.0


Solution

  • Yes, you'll be able to do this. Just inherit your control from the CompositeControl class interface and add any extender or control from the ACT project to the Controls collection the same way as you should do this with ordinal ASP.NET server controls. Also you can inherit existing control and implement INamingContainer interface but in this case you must call RenderChildren method manually from control's Render method:

    [DefaultProperty("Text")]
    [ToolboxData("<{0}:WatermarkedTextBox runat=server></{0}:WatermarkedTextBox>")]
    public class WatermarkedTextBox : TextBox, INamingContainer
    {
        private AjaxControlToolkit.TextBoxWatermarkExtender _watermarkExtender;
    
        public string WatermarkText
        {
            get
            {
                return ViewState["WatermarkText"] as string;
            }
            set
            {
                ViewState["WatermarkText"] = value;
            }
        }
    
        protected override void CreateChildControls()
        {
            Controls.Clear();
    
            this._watermarkExtender = new AjaxControlToolkit.TextBoxWatermarkExtender
            {
                ID = "wte",
                TargetControlID = this.ID,
                WatermarkText = this.WatermarkText
            };
            this.Controls.Add(_watermarkExtender);
        }
    
        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
            RenderChildren(writer);
        }
    }
    

    }