0

我正在嘗試使用谷歌地圖,爲此我做了一個用戶控件,我嘗試註冊一個JavaScript,但又像往常一樣,它沒有得到註冊,所以我試圖註冊它後面的代碼使用clientscript。但是,同樣的問題。它沒有被註冊。在用戶控件中調用javascript

以下代碼寫在usercontrol的頁面加載事件中。

ClientScriptManager script = Page.ClientScript; 

     if (!script.IsStartupScriptRegistered(this.GetType(), "scriptKey")) 
     { 
      StringBuilder sb = new StringBuilder(); 
      sb.AppendLine("function initialize() {"); 
      sb.AppendLine("var latlng = new google.maps.LatLng(%%LAT%%, %%LONG%%);"); 
      sb.AppendLine("var myOptions = {"); 
      sb.AppendLine("zoom: 8,"); 
      sb.AppendLine("center: latlng,"); 
      sb.AppendLine("mapTypeId: google.maps.MapTypeId.ROADMAP"); 
      sb.AppendLine("};"); 
      sb.AppendLine("var map = new google.maps.Map(document.getElementById(\"\"%%CLIENTID%%\"\"), myOptions);"); 
      sb.AppendLine("}"); 


      sb = sb.Replace("%%CLIENTID%%", this.ClientID); 


      sb = sb.Replace("%%LAT%%", (a1 == null ? 42.006160736084 : a1.latitude).ToString()); 
      sb = sb.Replace("%%LONG%%", (a1 == null ? -93.6386795043945 : a1.longitude).ToString()); 

      script.RegisterStartupScript(this.GetType(), "scriptKey", sb.ToString(), false); 

然後我嘗試在aspx頁面中使用這個控件。任何幫助,將不勝感激, 謝謝!

回答

2

您忘記了標籤。

 StringBuilder sb = new StringBuilder(); 
     sb.AppendLine("<script type=\"text/javascript\"> function initialize() {"); 
     ...... 
     ...... 
     ...... 
     ...... 
     sb = sb.Replace("%%LAT%%", (a1 == null ? 42.006160736084 : a1.latitude).ToString()); 
     sb = sb.Replace("%%LONG%%", (a1 == null ? -93.6386795043945 : a1.longitude).ToString()); 

     sb.Append("</script>"); 
+1

或者,如果他不想添加標籤,他可以將script.RegisterStartupScript的最後一個參數更改爲true,它會爲他添加腳本標籤。 – Adrian 2011-01-26 23:20:54

相關問題