ClientScriptManager.RegisterStartupScript Método
Definição
Sobrecargas
| RegisterStartupScript(Type, String, String) |
Registra o script de inicialização no objeto Page usando um tipo, uma chave e um literal de script.Registers the startup script with the Page object using a type, a key, and a script literal. |
| RegisterStartupScript(Type, String, String, Boolean) |
Registra o script de inicialização no objeto Page usando um tipo, uma chave, um literal de script e um valor booliano indicando se devem ser adicionadas marcas de script.Registers the startup script with the Page object using a type, a key, a script literal, and a Boolean value indicating whether to add script tags. |
RegisterStartupScript(Type, String, String)
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
O tipo de script de inicialização a ser registrado.The type of the startup script to register.
- key
- String
A chave do script de inicialização a ser registrada.The key of the startup script to register.
- script
- String
O literal do script de inicialização a ser registrado.The startup script literal to register.
Exemplos
O exemplo de código a seguir demonstra o uso do RegisterStartupScript método.The following code example demonstrates the use of the RegisterStartupScript method. Observe que as marcas de script de início e fechamento são incluídas no script parâmetro.Note that the beginning and closing script tags are included within the script parameter. Para que as marcas de script sejam adicionadas com base em uma configuração de parâmetro adicional, consulte o RegisterStartupScript método.To have the script tags added based on an additional parameter setting, see the RegisterStartupScript 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 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>
Comentários
Um script de cliente é identificado exclusivamente por sua chave e seu tipo.A client script is uniquely identified by its key and its type. Scripts com a mesma chave e tipo são considerados duplicatas.Scripts with the same key and type are considered duplicates. Somente um script com um determinado tipo e par de chaves pode ser registrado com a página.Only one script with a given type and key pair can be registered with the page. A tentativa de registrar um script que já está registrado não cria uma duplicata do script.Attempting to register a script that is already registered does not create a duplicate of the script.
Chame o IsStartupScriptRegistered método para determinar se um script de inicialização com um determinado par de chave e tipo já está registrado e evite tentar adicionar o script desnecessariamente.Call the IsStartupScriptRegistered method to determine whether a startup script with a given key and type pair is already registered and avoid unnecessarily attempting to add the script.
Nessa sobrecarga do RegisterStartupScript método, você deve certificar-se de que o script fornecido no script parâmetro seja encapsulado com um <script> bloco de elemento.In this overload of the RegisterStartupScript method, you must make sure that the script provided in the script parameter is wrapped with a <script> element block.
O bloco de script adicionado pelo RegisterStartupScript método é executado quando a página termina de ser carregada, mas antes de o evento da página OnLoad ser gerado.The script block added by the RegisterStartupScript method executes when the page finishes loading but before the page's OnLoad event is raised. Não há garantia de que os blocos de script sejam gerados na ordem em que estão registrados.The script blocks are not guaranteed to be output in the order they are registered. Se a ordem dos blocos de script for importante, use um StringBuilder objeto para coletar os scripts em uma única cadeia de caracteres e, em seguida, registre-os em um único bloco 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.
Confira também
Aplica-se a
RegisterStartupScript(Type, String, String, Boolean)
Registra o script de inicialização no objeto Page usando um tipo, uma chave, um literal de script e um valor booliano indicando se devem ser adicionadas marcas de script.Registers the startup script with the Page object using a type, a key, a script literal, and a Boolean value indicating whether to add script tags.
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
O tipo de script de inicialização a ser registrado.The type of the startup script to register.
- key
- String
A chave do script de inicialização a ser registrada.The key of the startup script to register.
- script
- String
O literal do script de inicialização a ser registrado.The startup script literal to register.
- addScriptTags
- Boolean
Um valor booliano que indica se deverão ser adicionadas marcas de script.A Boolean value indicating whether to add script tags.
Exceções
type é null.type is null.
Exemplos
O exemplo de código a seguir demonstra o uso do RegisterStartupScript método.The following code example demonstrates the use of the RegisterStartupScript method. Observe que o addScriptTags parâmetro é definido como para false que as marcas de script de início e fechamento sejam incluídas com o script parâmetro.Note that the addScriptTags parameter is set to false so the beginning and closing script tags are 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>
Comentários
Um script de inicialização é identificado exclusivamente por sua chave e seu tipo.A startup script is uniquely identified by its key and its type. Scripts com a mesma chave e tipo são considerados duplicatas.Scripts with the same key and type are considered duplicates. Somente um script com um determinado tipo e par de chaves pode ser registrado com a página.Only one script with a given type and key pair can be registered with the page. A tentativa de registrar um script que já está registrado não cria uma duplicata do script.Attempting to register a script that is already registered does not create a duplicate of the script.
Chame o IsStartupScriptRegistered método para determinar se um script de inicialização com um determinado par de chave e tipo já está registrado e evite tentar adicionar o script desnecessariamente.Call the IsStartupScriptRegistered method to determine whether a startup script with a given key and type pair is already registered and avoid unnecessarily attempting to add the script.
Nessa sobrecarga do RegisterStartupScript método, você pode indicar se o script fornecido no script parâmetro é encapsulado com um bloco de <script> elemento usando o addScriptTags parâmetro.In this overload of the RegisterStartupScript method, you can indicate whether the script provided in the script parameter is wrapped with a <script> element block by using the addScriptTags parameter. Configuração addScriptTags para true indicar que as marcas de script serão adicionadas automaticamente.Setting addScriptTags to true indicates that script tags will be added automatically.
O bloco de script adicionado pelo RegisterStartupScript método é executado quando a página termina de ser carregada, mas antes de o evento da página OnLoad ser gerado.The script block added by the RegisterStartupScript method executes when the page finishes loading but before the page's OnLoad event is raised. Não há garantia de que os blocos de script sejam gerados na ordem em que estão registrados.The script blocks are not guaranteed to be output in the order they are registered. Se a ordem dos blocos de script for importante, use um StringBuilder objeto para coletar os scripts em uma única cadeia de caracteres e, em seguida, registre-os em um único bloco 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.