ClientScriptManager.RegisterStartupScript Método

Definición

Registra el script de inicio con el objeto Page.

Sobrecargas

RegisterStartupScript(Type, String, String)

Registra el script de inicio con el objeto Page utilizando un tipo, una clave y un literal de script.

RegisterStartupScript(Type, String, String, Boolean)

Registra el script de inicio con el objeto Page utilizando un tipo, una clave, un literal de script y un valor booleano que indican si se agregan etiquetas de script.

RegisterStartupScript(Type, String, String)

Registra el script de inicio con el objeto Page utilizando un tipo, una clave y un literal de script.

public:
 void RegisterStartupScript(Type ^ type, System::String ^ key, System::String ^ script);
public void RegisterStartupScript (Type type, string key, string script);
member this.RegisterStartupScript : Type * string * string -> unit
Public Sub RegisterStartupScript (type As Type, key As String, script As String)

Parámetros

type
Type

Tipo del script de inicio que se va a registrar.

key
String

Clave del script de inicio que se va a registrar.

script
String

Literal del script de inicio que se va a registrar.

Ejemplos

En el ejemplo de código siguiente se muestra el uso del RegisterStartupScript método . Tenga en cuenta que las etiquetas de script inicial y de cierre se incluyen dentro del script parámetro . Para que las etiquetas de script se agreguen en función de una configuración de parámetro adicional, consulte el RegisterStartupScript método .

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
  public void Page_Load(Object sender, EventArgs e)
  {
    // Define the name and type of the client scripts on the page.
    String csname1 = "PopupScript";
    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> alert('Hello World!') </");
        cstext1.Append("script>");

        cs.RegisterStartupScript(cstype, csname1, cstext1.ToString());
    }
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>RegisterStartupScript</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    Public Sub Page_Load(ByVal sender As [Object], ByVal e As EventArgs)
        ' Define the name and type of the client scripts on the page. 
        Dim csname1 As [String] = "PopupScript"
        Dim cstype As Type = Me.[GetType]()
    
        ' Get a ClientScriptManager reference from the Page class. 
        Dim cs As ClientScriptManager = Page.ClientScript
    
        ' Check to see if the startup script is already registered. 
        If Not cs.IsStartupScriptRegistered(cstype, csname1) Then
            Dim cstext1 As New StringBuilder()
            cstext1.Append("<script type=text/javascript> alert('Hello World!') </")
            cstext1.Append("script>")
        
            cs.RegisterStartupScript(cstype, csname1, cstext1.ToString())
        End If
    End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>RegisterStartupScript</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

Comentarios

Un script de cliente se identifica de forma única por su clave y su tipo. Los scripts con la misma clave y tipo se consideran duplicados. Solo se puede registrar un script con un tipo determinado y un par de claves en la página. Si se intenta registrar un script que ya está registrado, no se crea un duplicado del script.

Llame al IsStartupScriptRegistered método para determinar si un script de inicio con una clave y un par de tipos especificados ya está registrado y evitar que se intente agregar el script innecesariamente.

En esta sobrecarga del RegisterStartupScript método , debe asegurarse de que el script proporcionado en el script parámetro se encapsula con un <script> bloque de elementos.

El bloque de script agregado por el RegisterStartupScript método se ejecuta cuando la página finaliza la carga, pero antes de que se genere el evento de OnLoad la página. No se garantiza que los bloques de script sean de salida en el orden en que están registrados. Si el orden de los bloques de script es importante, use un StringBuilder objeto para recopilar los scripts juntos en una sola cadena y, a continuación, regístrelos todos en un único bloque de script de cliente.

Consulte también

Se aplica a

RegisterStartupScript(Type, String, String, Boolean)

Registra el script de inicio con el objeto Page utilizando un tipo, una clave, un literal de script y un valor booleano que indican si se agregan etiquetas de script.

public:
 void RegisterStartupScript(Type ^ type, System::String ^ key, System::String ^ script, bool addScriptTags);
public void RegisterStartupScript (Type type, string key, string script, bool addScriptTags);
member this.RegisterStartupScript : Type * string * string * bool -> unit
Public Sub RegisterStartupScript (type As Type, key As String, script As String, addScriptTags As Boolean)

Parámetros

type
Type

Tipo del script de inicio que se va a registrar.

key
String

Clave del script de inicio que se va a registrar.

script
String

Literal del script de inicio que se va a registrar.

addScriptTags
Boolean

Valor booleano que indica si se agregan etiquetas de script.

Excepciones

type es null.

Ejemplos

En el ejemplo de código siguiente se muestra el uso del RegisterStartupScript método . Tenga en cuenta que el addScriptTags parámetro se establece en false para que las etiquetas de script inicial y de cierre se incluyan con el script parámetro .

<%@ Page Language="C#"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
  public void Page_Load(Object sender, EventArgs e)
  {
    // Define the name and type of the client scripts on the page.
    String csname1 = "PopupScript";
    String csname2 = "ButtonClickScript";
    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))
    {
      String cstext1 = "alert('Hello World');";
      cs.RegisterStartupScript(cstype, csname1, cstext1, true);
    }

    // Check to see if the client script is already registered.
    if (!cs.IsClientScriptBlockRegistered(cstype, csname2))
    {
      StringBuilder cstext2 = new StringBuilder();
      cstext2.Append("<script type=\"text/javascript\"> function DoClick() {");
      cstext2.Append("Form1.Message.value='Text from client script.'} </");
      cstext2.Append("script>");
      cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
    }
  }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>ClientScriptManager Example</title>
  </head>
  <body>
     <form id="Form1"
         runat="server">
        <input type="text" id="Message" /> <input type="button" value="ClickMe" onclick="DoClick()" />
     </form>
  </body>
</html>
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

    ' Define the name and type of the client scripts on the page.
    Dim csname1 As String = "PopupScript"
    Dim csname2 As String = "ButtonClickScript"
    Dim cstype As Type = Me.GetType()
    
    ' Get a ClientScriptManager reference from the Page class.
    Dim cs As ClientScriptManager = Page.ClientScript

    ' Check to see if the startup script is already registered.
    If (Not cs.IsStartupScriptRegistered(cstype, csname1)) Then
      
      Dim cstext1 As String = "alert('Hello World');"
      cs.RegisterStartupScript(cstype, csname1, cstext1, True)
      
    End If
    
    ' Check to see if the client script is already registered.
    If (Not cs.IsClientScriptBlockRegistered(cstype, csname2)) Then
      
      Dim cstext2 As New StringBuilder()
            cstext2.Append("<script type=""text/javascript""> function DoClick() {")
      cstext2.Append("Form1.Message.value='Text from client script.'} </")
      cstext2.Append("script>")
      cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), False)
      
    End If
    
  End Sub
  
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>ClientScriptManager Example</title>
  </head>
  <body>
     <form id="Form1"
         runat="server">
        <input type="text" id="Message" /> <input type="button" value="ClickMe" onclick="DoClick()" />
     </form>
  </body>
</html>

Comentarios

Un script de inicio se identifica de forma única por su clave y su tipo. Los scripts con la misma clave y tipo se consideran duplicados. Solo se puede registrar un script con un tipo determinado y un par de claves en la página. Si se intenta registrar un script que ya está registrado, no se crea un duplicado del script.

Llame al IsStartupScriptRegistered método para determinar si un script de inicio con una clave y un par de tipos especificados ya está registrado y evitar que se intente agregar el script innecesariamente.

En esta sobrecarga del RegisterStartupScript método, puede indicar si el script proporcionado en el script parámetro se ajusta con un <script> bloque de elementos mediante el addScriptTags parámetro . Establecer addScriptTags en true indica que las etiquetas de script se agregarán automáticamente.

El bloque de script agregado por el RegisterStartupScript método se ejecuta cuando la página finaliza la carga, pero antes de que se genere el evento de OnLoad la página. No se garantiza que los bloques de script sean de salida en el orden en que están registrados. Si el orden de los bloques de script es importante, use un StringBuilder objeto para recopilar los scripts juntos en una sola cadena y, a continuación, regístrelos todos en un único bloque de script de cliente.

Consulte también

Se aplica a