Question

In my ASP.NET 4.0 web application, I have a class which is derived from a standard ASP.NET <asp:TextBox>. This class needs to add client-side script, but the script only needs to be added to the page once even if there are multiple instances of the control on the page.

As I cannot access the ViewState of the page, what is best practise for making sure only the first control renders the script to the page.

I cannot use a static variable, as I obviously need it to be per-page... not per session/application.

This is roughly what I have at the moment...

Public Class MyTextBox
  Inherits TextBox

  Private Sub MyTextBox_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender
    Dim script As String = "window.alert('Hello World');"
    Page.ClientScript.RegisterStartupScript(Me.GetType(), "myscript", script, True)
  End Sub
End Class

Just to be clear - this is not a post-back issue, but only rendering the script on the first instance of the control within the page (whether in the page itself, or from a user control).

Was it helpful?

Solution

You can use ClientScript.IsStartupScriptRegistered to check if it's already registered:

Public Class MyTextBox
    Inherits TextBox

    Private Sub MyTextBox_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender
        If Not Page.ClientScript.IsStartupScriptRegistered("AlertHelloWorld") Then
            Dim alertHelloWorld = "window.alert('Hello World');"
            Page.ClientScript.RegisterStartupScript(GetType(MyTextBox), "AlertHelloWorld", alertHelloWorld, True)
        End If
    End Sub

End Class
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top