问题描述:

What is the best method to register a stylesheet once on a page from a customer web control? Please keep in mind that the page uses an UpdatePanel for async calls. I tried just putting the <link> tag in ScriptManager.RegisterClientScriptBlock(), but I get this error:

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.

If I try to add it to the page by adding it to the control hierarchy, it shows up once for each instance of my control on the page.

网友答案:

Well, here's what I went with. I decided to create extension methods that will include the link.

Update: I had to change the ScriptManager extension as it still was not playing nice with UpdatePanels. Updated code is below.

    <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
相关阅读:
Top