2016-01-23 143 views
0

Visual Studio 2013,C#代碼。自定義服務器控件觸發器頁面加載JS文件

要求明確定義爲使用從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事件裏面的按鈕& Label控件。

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

必須使用自定義服務器控件中PageScriptManager registred JS文件。 CustomerJS文件,該文件與該控件相關,專門用於處理客戶端功能。

使用Render/OnLoad Events註冊腳本。

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

     } 

的問題是:該Customer.JS文件獲取調用該主頁被完全呈現之前,但要當這實際上是使用自定義控制頁面完全加載它被觸發。就像在jquery中的document.ready函數一樣。

要點:1。 服務器控制應該是獨立的實體,所以不能用Jquery的 插件(或任何其他)
2. Customer.Js文件是純JavaScript文件
3.不必添加Customer.JS主 頁面理由再次文件引用開始引用已經存在的自定義服務器控件

主要問題:1。 如何調用Customer.JS文件,使之被加載後,主要就是頁面完全讀取。 2.客戶.JS文件應該只在自定義服務器控制中引用,而不在其他地方。

+0

檢查我的答案,並告訴我是否有幫助。 – mybirthname

回答

1

使用

ClientScript.RegisterStartupScript 

這將</body>標籤後加載JavaScript,所以頁面應該已經被加載。

+0

更詳細的解釋:https://msdn.microsoft.com/en-us/library/bb398930.aspx – Vinod

+0

https://www.youtube.com/watch?v=FXZ0KSuIOKM – Vinod

相關問題