ClientScriptManager.RegisterClientScriptBlock Método

Definición

Registra el script de cliente con el objeto Page.Registers the client script with the Page object.

Sobrecargas

RegisterClientScriptBlock(Type, String, String)

Registra el script de cliente con el objeto Page utilizando un tipo, clave y literal de script.Registers the client script with the Page object using a type, key, and script literal.

RegisterClientScriptBlock(Type, String, String, Boolean)

Registra el script de cliente con el objeto Page utilizando un tipo, clave, literal de script y valor booleano que indican si se agregan etiquetas de script.Registers the client script with the Page object using a type, key, script literal, and Boolean value indicating whether to add script tags.

RegisterClientScriptBlock(Type, String, String)

Registra el script de cliente con el objeto Page utilizando un tipo, clave y literal de script.Registers the client script with the Page object using a type, key, and script literal.

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

Parámetros

type
Type

Tipo del script de cliente que se va a registrar.The type of the client script to register.

key
String

Clave del script de cliente que se va a registrar.The key of the client script to register.

script
String

Literal del script de cliente que se va a registrar.The client script literal to register.

Ejemplos

En el ejemplo de código siguiente se muestra el RegisterClientScriptBlock uso del método.The following code example demonstrates the use of the RegisterClientScriptBlock method.

<%@ 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 script on the page.
    String csName = "ButtonClickScript";
    Type csType = this.GetType();

    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = Page.ClientScript;

    // Check to see if the client script is already registered.
    if (!cs.IsClientScriptBlockRegistered(csType, csName))
    {
      StringBuilder csText = new StringBuilder();
      csText.Append("<script type=\"text/javascript\"> function DoClick() {");
      csText.Append("Form1.Message.value='Text from client script.'; }");
      csText.Append("</script>");
      cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
    }
  }
</script>
<html  >
  <head>
    <title>RegisterClientScriptBlock 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">
    Public Sub Page_Load(ByVal sender As [Object], ByVal e As EventArgs)
        ' Define the name and type of the client script on the page. 
        Dim csName 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 client script is already registered. 
        If Not cs.IsClientScriptBlockRegistered(csType, csName) Then
            Dim csText As New StringBuilder()
            csText.Append("<script type=""text/javascript""> function DoClick() {")
            csText.Append("Form1.Message.value='Text from client script.'; }")
            csText.Append("</script>")
            cs.RegisterClientScriptBlock(csType, csName, csText.ToString())
        End If
    End Sub
</script>
<html  >
  <head>
    <title>RegisterClientScriptBlock 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 cliente se identifica de forma única mediante su clave y su tipo.A client script is uniquely identified by its key and its type. Los scripts con la misma clave y tipo se consideran duplicados.Scripts with the same key and type are considered duplicates. Solo se puede registrar en la página un script con un tipo y un par de claves determinados.Only one script with a given type and key pair can be registered with the page. Al intentar registrar un script que ya está registrado, no se crea un duplicado del script.Attempting to register a script that is already registered does not create a duplicate of the script.

Llame al IsClientScriptBlockRegistered método para determinar si ya se ha registrado un script de cliente con una clave y un par de tipos determinados y evitar intentos innecesarios de agregar el script.Call the IsClientScriptBlockRegistered method to determine whether a client script with a given key and type pair is already registered and avoid unnecessarily attempting to add the script.

En esta sobrecarga del RegisterClientScriptBlock método, debe asegurarse de que el script proporcionado en el script parámetro se ajusta en un <script> bloque de elementos.In this overload of the RegisterClientScriptBlock method, you must make sure that the script provided in the script parameter is wrapped in a <script> element block.

El RegisterClientScriptBlock método agrega un bloque de script a la parte superior de la página representada.The RegisterClientScriptBlock method adds a script block to the top of the rendered page. No se garantiza que los bloques de script se generen en el orden en que se registraron.The script blocks are not guaranteed to be output in the order they are registered. Si el orden de los bloques de script es importante, use StringBuilder un objeto para recopilar los scripts juntos en una sola cadena y, a continuación, regístrelo en un solo bloque de script de cliente.If the order of the script blocks is important, use a StringBuilder object to gather the scripts together in a single string, and then register them all in a single client script block.

Consulte también:

RegisterClientScriptBlock(Type, String, String, Boolean)

Registra el script de cliente con el objeto Page utilizando un tipo, clave, literal de script y valor booleano que indican si se agregan etiquetas de script.Registers the client script with the Page object using a type, key, script literal, and Boolean value indicating whether to add script tags.

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

Parámetros

type
Type

Tipo del script de cliente que se va a registrar.The type of the client script to register.

key
String

Clave del script de cliente que se va a registrar.The key of the client script to register.

script
String

Literal del script de cliente que se va a registrar.The client script literal to register.

addScriptTags
Boolean

Valor booleano que indica si se agregan etiquetas de script.A Boolean value indicating whether to add script tags.

Excepciones

El tipo del bloque de script de cliente es null.The client script block type is null.

Ejemplos

En el ejemplo de código siguiente se muestra el RegisterClientScriptBlock uso del método.The following code example demonstrates the use of the RegisterClientScriptBlock method. Tenga en cuenta addScriptTags que el parámetro se true establece en para que las etiquetas de script de inicio y cierre script no se incluyan con el parámetro.Note that the addScriptTags parameter is set to true so the beginning and closing script tags are not included with the script parameter.

<%@ 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 cliente se identifica de forma única mediante su clave y su tipo.A client script is uniquely identified by its key and its type. Los scripts con la misma clave y tipo se consideran duplicados.Scripts with the same key and type are considered duplicates. Solo se puede registrar en la página un script con un tipo y un par de claves determinados.Only one script with a given type and key pair can be registered with the page. Al intentar registrar un script que ya está registrado, no se crea un duplicado del script.Attempting to register a script that is already registered does not create a duplicate of the script.

Llame al IsClientScriptBlockRegistered método para determinar si ya se ha registrado un script de cliente con un par de clave y tipo determinado.Call the IsClientScriptBlockRegistered method to determine whether a client script with a given key and type pair is already registered. Esto le permite evitar intentos innecesarios de agregar el script.This lets you avoid unnecessarily attempting to add the script.

En esta sobrecarga RegisterClientScriptBlock del 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.In this overload of the RegisterClientScriptBlock method, you can indicate whether the script provided in the script parameter is wrapped with a <script> element block by using the addScriptTags parameter. Si addScriptTags se true establece en, indica que las etiquetas de script se agregarán automáticamente.Setting addScriptTags to true indicates that script tags will be added automatically.

El RegisterClientScriptBlock método agrega un bloque de script a la parte superior de la página representada.The RegisterClientScriptBlock method adds a script block to the top of the rendered page. No se garantiza que los bloques de script se generen en el orden en que se registraron.The script blocks are not guaranteed to be output in the order they are registered. Si el orden de los bloques de script es importante, use StringBuilder un objeto para recopilar los scripts juntos en una sola cadena y, a continuación, regístrelo en un solo bloque de script de cliente.If the order of the script blocks is important, use a StringBuilder object to gather the scripts together in a single string, and then register them all in a single client script block.

Consulte también:

Se aplica a