2010-07-27 42 views
2

在客戶Web控件的頁面上註冊樣式表一次的最佳方法是什麼?請記住,該頁面使用UpdatePanel進行異步調用。我嘗試了投入ScriptManager.RegisterClientScriptBlock()的<link>標籤,但我得到這個錯誤:使用UpdatePanel在頁面上註冊來自Web控件的樣式表

The script tag registered for type 'MyControl' and key 'MyKey' has invalid characters outside of the script tags: . Only properly formatted script tags can be registered.

如果我試圖將它添加到控制層次,將其添加到頁面,它顯示了每進行一次我的控件在頁面上的實例。

回答

3

嗯,這就是我的意見。我決定創建包含鏈接的擴展方法。

更新:我不得不更改ScriptManager擴展,因爲它仍然不能很好地與UpdatePanels配合使用。更新後的代碼如下。

<System.Runtime.CompilerServices.Extension()> _ 
    Public Sub RegisterStylesheetInclude(ByVal scriptManager As ScriptManager, ByVal page As Page, ByVal url As String) 
     Dim css = "var cssNode = document.createElement('link');" & _ 
     "cssNode.type = 'text/css';" & _ 
     "cssNode.rel = 'stylesheet';" & _ 
     "cssNode.href = '" & url & "';" & _ 
     "document.getElementsByTagName('head')[0].appendChild(cssNode);" 

     scriptManager.RegisterClientScriptBlock(page, page.GetType(), url, css, True) 
    End Sub 

    <System.Runtime.CompilerServices.Extension()> _ 
    Public Sub RegisterStylesheetInclude(ByVal clientScriptManager As ClientScriptManager, ByVal page As Page, ByVal url As String) 
     Dim found = page.Header.Controls.OfType(Of HtmlLink).Any(Function(m) m.Href = url) 

     If Not found Then 
      Dim link As New HtmlLink() 
      link.Href = url 
      link.Attributes("type") = "text/css" 
      link.Attributes("rel") = "stylesheet" 
      page.Header.Controls.Add(link) 
     End If 
    End Sub