ClientScriptManager.RegisterClientScriptBlock Метод
Определение
Перегрузки
RegisterClientScriptBlock(Type, String, String) |
Регистрирует клиентский скрипт с объектом Page, используя тип, ключ и константу скрипта.Registers the client script with the Page object using a type, key, and script literal. |
RegisterClientScriptBlock(Type, String, String, Boolean) |
Регистрирует клиентский скрипт с объектом Page, используя тип, ключ, константу скрипта и логическое значение, указывающее следует ли добавление тегов скрипта.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)
Регистрирует клиентский скрипт с объектом Page, используя тип, ключ и константу скрипта.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
Параметры
- type
- Type
Тип регистрируемого клиентского скрипта.The type of the client script to register.
- key
- String
Ключ регистрируемого клиентского скрипта.The key of the client script to register.
- script
- String
Константа регистрируемого клиентского скрипта.The client script literal to register.
Примеры
В следующем примере кода показано использование RegisterClientScriptBlock метода.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>
Комментарии
Клиентский скрипт однозначно идентифицируется по ключу и типу.A client script is uniquely identified by its key and its type. Скрипты с одинаковыми ключом и типом считаются дубликатами.Scripts with the same key and type are considered duplicates. На странице можно зарегистрировать только один скрипт с заданным типом и парой ключей.Only one script with a given type and key pair can be registered with the page. При попытке регистрации скрипта, который уже зарегистрирован, не создается дубликат скрипта.Attempting to register a script that is already registered does not create a duplicate of the script.
Вызовите IsClientScriptBlockRegistered метод, чтобы определить, уже зарегистрирован ли клиентский скрипт с заданным ключом и парой типов, и избежать ненужной попытки добавить скрипт.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.
В этой перегрузке RegisterClientScriptBlock метода необходимо убедиться, что скрипт, предоставленный script
в <script>
параметре, заключен в блок element.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.
RegisterClientScriptBlock Метод добавляет блок скрипта в верхнюю часть отображаемой страницы.The RegisterClientScriptBlock method adds a script block to the top of the rendered page. Не гарантируется, что блоки сценариев будут выводиться в том порядке, в котором они зарегистрированы.The script blocks are not guaranteed to be output in the order they are registered. Если важен порядок блоков скрипта, используйте StringBuilder объект для сбора скриптов в одной строке, а затем зарегистрируйте их в одном блоке клиентского сценария.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.
Дополнительно
RegisterClientScriptBlock(Type, String, String, Boolean)
Регистрирует клиентский скрипт с объектом Page, используя тип, ключ, константу скрипта и логическое значение, указывающее следует ли добавление тегов скрипта.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
Параметры
- type
- Type
Тип регистрируемого клиентского скрипта.The type of the client script to register.
- key
- String
Ключ регистрируемого клиентского скрипта.The key of the client script to register.
- script
- String
Константа регистрируемого клиентского скрипта.The client script literal to register.
- addScriptTags
- Boolean
Логическое значение, указывающее, требуется ли добавление тегов скрипта.A Boolean value indicating whether to add script tags.
Исключения
Тип блока клиентского скрипта — null
.The client script block type is null
.
Примеры
В следующем примере кода показано использование RegisterClientScriptBlock метода.The following code example demonstrates the use of the RegisterClientScriptBlock method. Обратите внимание addScriptTags
, что параметр имеет true
значение, поэтому начальный и закрывающий теги скрипта не включаются script
в параметр.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>
Комментарии
Клиентский скрипт однозначно идентифицируется по ключу и типу.A client script is uniquely identified by its key and its type. Скрипты с одинаковыми ключом и типом считаются дубликатами.Scripts with the same key and type are considered duplicates. На странице можно зарегистрировать только один скрипт с заданным типом и парой ключей.Only one script with a given type and key pair can be registered with the page. При попытке регистрации скрипта, который уже зарегистрирован, не создается дубликат скрипта.Attempting to register a script that is already registered does not create a duplicate of the script.
Вызовите IsClientScriptBlockRegistered метод, чтобы определить, уже зарегистрирован ли клиентский скрипт с заданной парой ключей и типов.Call the IsClientScriptBlockRegistered method to determine whether a client script with a given key and type pair is already registered. Это позволяет избежать ненужной попытки добавить скрипт.This lets you avoid unnecessarily attempting to add the script.
В этой перегрузке RegisterClientScriptBlock метода можно указать, упакован ли скрипт, предоставленный script
в <script>
параметре, блоком элементов с помощью addScriptTags
параметра.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. Значение addScriptTags
указывает,что тегискриптабудутдобавлятьсяавтоматически.true
Setting addScriptTags
to true
indicates that script tags will be added automatically.
RegisterClientScriptBlock Метод добавляет блок скрипта в верхнюю часть отображаемой страницы.The RegisterClientScriptBlock method adds a script block to the top of the rendered page. Не гарантируется, что блоки сценариев будут выводиться в том порядке, в котором они зарегистрированы.The script blocks are not guaranteed to be output in the order they are registered. Если важен порядок блоков скрипта, используйте StringBuilder объект для сбора скриптов в одной строке, а затем зарегистрируйте их в одном блоке клиентского сценария.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.