Vinod
Vinod

Reputation: 566

Custom Server Control trigger Page Load JS file

Visual Studio 2013 , C# Code.

Requirements are clearly defined to use a Custom Server Control which inherits from WebControl base class.

  [ToolboxData("<{0}:SampleTemplate runat=server></{0}:SampleTemplate>")]
        public class SampleTemplate : WebControl, INamingContainer
        {
            Private Button btnCustomer;
            Private Label lblCountry;
            private const string _JAVASCRIPT_URL = "/Scripts/ServerControlUtility/Customer.js";

Have Initialized the Button & Label control inside the CreateChildControls event.

protected override void CreateChildControls()
        {
            Controls.Clear();
            lblCountry = new Label();
            lblCountry.ID = "Country";

            btnCustomer = new Button();
            btnCustomer.ID = "btnLookUpAddress";
            btnCustomer.Text = "Look Up Address";
            Controls.Add(btnCustomer);
        }

Have registred JS file by using the PageScriptManager inside the Custom Server Control. CustomerJS file which is related specific to this control which take care of Client Side Features.

Used the Render/OnLoad Events to register the Script.

protected override void Render(HtmlTextWriter writer)
        {
            var p = (Page)System.Web.HttpContext.Current.Handler;
            ScriptManager.RegisterClientScriptInclude(p, p.GetType(), "CustomerExtendedScript", _JAVASCRIPT_URL);

        }

The Problem is : The Customer.JS file is getting called before the Main Page is fully Rendered But want it to get Triggered when the Page which is actually using the Custom control is fully loaded. Just like an document.ready function in Jquery.

Important Points : 1. Server Control should be independent entity so can't use the Jquery Plugin ( or any other )
2. Customer.Js file is pure Javascript file
3. Need not add the Customer.JS file reference again in main page reason begin the reference is already there in Custom Server Control

Main Question: 1. How to call the Customer.JS file such that it gets loaded after the Main Page is fully loaded. 2. Customer.JS file should be only refered at Custom Server Control and no where else again.

Upvotes: 0

Views: 158

Answers (1)

mybirthname
mybirthname

Reputation: 18137

Use

ClientScript.RegisterStartupScript

This will load the javascript after the </body> tag, so the page should be loaded already.

Upvotes: 1

Related Questions