自定义服务器控件触发器页面加载 JS 文件



>Visual Studio 2013 , C# Code.

明确定义了使用从 WebControl 基类继承的自定义服务器控件的要求。

  [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";

已初始化 CreateChildControls 事件中的按钮和标签控件。

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

通过使用自定义服务器控件中的页面脚本管理器注册 JS 文件。客户JS文件,它与特定于此控件相关,负责客户端功能。

使用 render/onLoad 事件来注册脚本。

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

问题是:在主页完全呈现之前调用客户.JS文件,但希望在实际使用自定义控件的页面完全加载时触发它。就像Jquery中的document.ready函数一样。

要点 : 1. 服务器控件应该是独立的实体,因此不能使用 Jquery 插件(或任何其他)
2. Customer.js 文件是纯 Javascript 文件
3. 无需在主页中再次添加客户.JS文件引用 原因开始引用已在自定义服务器控件中存在

主要问题:1. 如何调用 Customer.JS 文件,以便在主页完全加载后加载该文件。2. 客户.JS文件应仅在自定义服务器控件中引用,而不应再在其他位置引用。

使用

ClientScript.RegisterStartupScript

这将在 </body> 标记之后加载 javascript,因此页面应该已经加载。

最新更新