2012-07-17 76 views
1

如何在自己的服務器控件中實現DevExpress用於其控件的ClientInstanceName屬性?如何實現ASP.Net複合服務器控件的ClientInstanceName屬性

ClientID屬性是隻讀的。這是否意味着我將不得不等待,直到HTML生成,然後替換名稱屬性?

有沒有辦法在c#中做到這一點,或者我必須在JavaScript中做到這一點?

在此先感謝。

+0

你可以改變它們是如何產生的。這有幫助嗎?如果不是,爲什麼?你想達到什麼目的? – Andre 2012-07-17 18:33:37

+0

我不想改變它們的生成方式。我想添加一個名爲ClientInstanceName的新屬性來覆蓋生成的名稱,以便可以在設計時設置該名稱。 – Soenhay 2012-07-17 18:45:32

回答

1

這裏是我想出了(有任何建議或改進,將不勝感激):

  private String _ClientInstanceName; 

      /// <summary> 
      /// Gets or Sets the client instance name. 
      /// </summary> 
      [ 
      Bindable(true), Category("Client-Side"), 
      DefaultValue(""), Description("The ClientInstanceName can be used to reference this control on the client.") 
      ] 
      public String ClientInstanceName 
      { 
       get 
       { 
        return _ClientInstanceName; 
       } 
       set 
       { 
        _ClientInstanceName= value; 
       } 
      } 


     protected override void OnPreRender(EventArgs e) 
     { 
      base.OnPreRender(e); 

      //Register startup script for creating JavaScript reference to this server control object. 
      if (this.ClientInstanceName.Length > 0) { registerClientInstanceName(this.ClientInstanceName, this.ClientID); } 
     } 

     /// <summary> 
     /// Create a JavaScript reference to the Object with ClientID using the ClientInstanceName property. 
     /// Based on: http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx 
     /// </summary> 
     /// <param name="ClientInstanceName"></param> 
     private void registerClientInstanceName(String ClientInstanceName, String ClientID) 
     { 
      // Define the name and type of the client scripts on the page. 
      String csname1 = "ClientInstanceNameScript"; 
      Type cstype = this.GetType(); 

      // Get a ClientScriptManager reference from the Page class. 
      ClientScriptManager cs = Page.ClientScript; 

      // Check to see if the startup script is already registered. 
      if (!cs.IsStartupScriptRegistered(cstype, csname1)) 
      { 
       StringBuilder cstext1 = new StringBuilder(); 
       cstext1.Append("<script type=text/javascript>"); 
       cstext1.Append("window['" + ClientInstanceName + "']=document.getElementById('" + ClientID + "');"); 
       cstext1.Append("</script>"); 

       cs.RegisterStartupScript(cstype, csname1, cstext1.ToString()); 
      } 
     } 
相關問題