ScriptReference Classe
Definição
Registra um arquivo ECMAScript (JavaScript) para uso em uma página da Web do ASP.NET.Registers an ECMAScript (JavaScript) file for use on an ASP.NET Web page.
public ref class ScriptReference : System::Web::UI::ScriptReferenceBase
public class ScriptReference : System.Web.UI.ScriptReferenceBase
type ScriptReference = class
inherit ScriptReferenceBase
Public Class ScriptReference
Inherits ScriptReferenceBase
- Herança
Exemplos
O exemplo a seguir mostra como fazer referência a um controle personalizado e a um arquivo JavaScript inserido no assembly de controle.The following example shows how to reference a custom control and a JavaScript file that is embedded in the control assembly. Supõe-se que o assembly esteja na pasta bin do site da Web.The assembly is assumed to be in the Bin folder of the Web site. O controle personalizado anima os UpdatePanel controles.The custom control animates UpdatePanel controls. O arquivo JavaScript é compilado como um recurso inserido chamado SampleControl.UpdatePanelAnimation.js.The JavaScript file is compiled as an embedded resource that is named SampleControl.UpdatePanelAnimation.js. Registre o arquivo JavaScript inserido usando as Assembly Name Propriedades e.You register the embedded JavaScript file by using the Assembly and Name properties.
Para usar este exemplo, compile o arquivo JavaScript que é mostrado no exemplo como um recurso incorporado com o controle personalizado.To use this example, compile the JavaScript file that is shown in the example as an embedded resource with the custom control. Coloque o assembly resultante na pasta bin do site da Web.Put the resulting assembly into the Bin folder of the Web site. Para obter um exemplo de como inserir um arquivo JavaScript em um assembly, consulte Walkthrough: inserindo um arquivo JavaScript como um recurso em um assembly.For an example of how to embed a JavaScript file in an assembly, see Walkthrough: Embedding a JavaScript File as a Resource in an Assembly.
O exemplo a seguir mostra uma página que usa o controle personalizado.The following example shows a page that uses the custom control.
<%@ Page Language="C#" %>
<%@ Register TagPrefix="Samples" Namespace="SampleControl" Assembly="SampleControl" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ScriptReference</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1"
EnablePartialRendering="True"
runat="server">
<Scripts>
<asp:ScriptReference Assembly="SampleControl" Name="SampleControl.UpdatePanelAnimation.js" />
</Scripts>
</asp:ScriptManager>
<Samples:UpdatePanelAnimationWithClientResource
ID="UpdatePanelAnimator1"
BorderColor="Green"
Animate="true"
UpdatePanelID="UpdatePanel1"
runat="server" >
</Samples:UpdatePanelAnimationWithClientResource>
<asp:UpdatePanel ID="UpdatePanel1"
UpdateMode="Conditional"
runat="server">
<ContentTemplate>
<asp:Calendar ID="Calendar2"
runat="server">
</asp:Calendar>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
<%@ Page Language="VB" AutoEventWireup="true" %>
<%@ Register TagPrefix="Samples" Namespace="SampleControl" Assembly="SampleControl" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>ScriptReference</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1"
EnablePartialRendering="True"
runat="server">
<Scripts>
<asp:ScriptReference Assembly="SampleControl" Name="SampleControl.UpdatePanelAnimation.js" />
</Scripts>
</asp:ScriptManager>
<Samples:UpdatePanelAnimationWithClientResource
ID="UpdatePanelAnimator1"
BorderColor="Green"
Animate="true"
UpdatePanelID="UpdatePanel1"
runat="server" >
</Samples:UpdatePanelAnimationWithClientResource>
<asp:UpdatePanel ID="UpdatePanel1"
UpdateMode="Conditional"
runat="server">
<ContentTemplate>
<asp:Calendar ID="Calendar2"
runat="server">
</asp:Calendar>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
O exemplo a seguir mostra a definição de classe de controle personalizado.The following example shows the custom control class definition.
using System;
using System.Drawing;
using System.Web.UI;
using System.Web;
using System.Globalization;
namespace SampleControl
{
public class UpdatePanelAnimationWithClientResource : Control
{
private string _updatePanelID;
private Color _borderColor;
private Boolean _animate;
public Color BorderColor
{
get
{
return _borderColor;
}
set
{
_borderColor = value;
}
}
public string UpdatePanelID
{
get
{
return _updatePanelID;
}
set
{
_updatePanelID = value;
}
}
public Boolean Animate
{
get
{
return _animate;
}
set
{
_animate = value;
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (Animate)
{
UpdatePanel updatePanel = (UpdatePanel)FindControl(UpdatePanelID);
string script = String.Format(
CultureInfo.InvariantCulture,
@"
Sys.Application.add_load(function(sender, args) {{
var {0}_borderAnimation = new BorderAnimation('{1}');
var panelElement = document.getElementById('{0}');
if (args.get_isPartialLoad()) {{
{0}_borderAnimation.animate(panelElement);
}}
}})
",
updatePanel.ClientID,
ColorTranslator.ToHtml(BorderColor));
ScriptManager.RegisterStartupScript(
this,
typeof(UpdatePanelAnimationWithClientResource),
ClientID,
script,
true);
}
}
}
}
Imports System.Web.UI
Imports System.Drawing
Imports System.Globalization
Public Class UpdatePanelAnimationWithClientResource
Inherits Control
Private _updatePanelID As String
Private _borderColor As Color
Private _animate As Boolean
Public Property BorderColor() As Color
Get
Return _borderColor
End Get
Set(ByVal value As Color)
_borderColor = value
End Set
End Property
Public Property UpdatePanelID() As String
Get
Return _updatePanelID
End Get
Set(ByVal value As String)
_updatePanelID = value
End Set
End Property
Public Property Animate() As Boolean
Get
Return _animate
End Get
Set(ByVal value As Boolean)
_animate = value
End Set
End Property
Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
MyBase.OnPreRender(e)
If (Animate) Then
Dim updatePanel As UpdatePanel = CType(Me.FindControl(UpdatePanelID), UpdatePanel)
Dim script As String = String.Format( _
CultureInfo.InvariantCulture, _
"Sys.Application.add_load(function(sender, args) {{var {0}_borderAnimation = new BorderAnimation('{1}');var panelElement = document.getElementById('{0}');if (args.get_isPartialLoad()) {{{0}_borderAnimation.animate(panelElement);}}}});", _
updatePanel.ClientID, _
ColorTranslator.ToHtml(BorderColor))
ScriptManager.RegisterStartupScript( _
Me, _
GetType(UpdatePanelAnimationWithClientResource), _
ClientID, _
script, _
True)
End If
End Sub
End Class
O exemplo a seguir mostra o arquivo JavaScript de suporte.The following example shows the supporting JavaScript file.
BorderAnimation = function(color) {
this._color = color;
}
BorderAnimation.prototype = {
animate: function(panelElement) {
var s = panelElement.style;
s.borderWidth = '2px';
s.borderColor = this._color;
s.borderStyle = 'solid';
window.setTimeout(
function() {{
s.borderWidth = 0;
}},
500);
}
}
O exemplo a seguir mostra o código que você deve adicionar ao arquivo AssemblyInfo do projeto que contém o controle personalizado e o arquivo JavaScript.The following example shows code that you must add to the AssemblyInfo file of the project that contains the custom control and the JavaScript file.
[assembly: System.Web.UI.WebResource("SampleControl.UpdatePanelAnimation.js", "application/x-javascript")]
<Assembly: System.Web.UI.WebResource("SampleControl.UpdatePanelAnimation.js", "application/x-javascript")>
Comentários
Você pode incluir um arquivo JavaScript em uma página da Web do ASP.NET, registrando-o por meio de um ScriptReference objeto.You can include a JavaScript file on an ASP.NET Web page by registering it through a ScriptReference object. Você pode registrar um arquivo de script que está localizado como um arquivo. js (um arquivo de script estático) no site.You can register a script file that is located as a .js file (a static script file) on the Web site. Você também pode registrar um arquivo de script que é inserido como um recurso em um assembly.You can also register a script file that is embedded as a resource in an assembly. Depois de registrar o arquivo de script, você pode usar suas funções no script de cliente na página da Web.After registering the script file, you can use its functions in client script on the Web page.
Para registrar um arquivo de script estático, defina a Path Propriedade do ScriptReference objeto como o local relativo do arquivo.To register a static script file, set the Path property of the ScriptReference object to the relative location of the file.
Para registrar um arquivo de script que é inserido como um recurso em um assembly, defina a Assembly propriedade como o nome do assembly que contém o arquivo.To register a script file that is embedded as a resource in an assembly, set the Assembly property to the name of the assembly that contains the file. Em seguida, defina a Name propriedade como o nome do arquivo. js inserido no assembly.Then set the Name property to the name of the .js file that is embedded in the assembly. Nesse caso, o arquivo de script deve ser inserido, não vinculado.In that case, the script file must be embedded, not linked.
Você define a ScriptMode propriedade para indicar se deve usar a versão de depuração ou de lançamento do script.You set the ScriptMode property to indicate whether to use the debug or release version of the script.
O Auto valor produz resultados diferentes dependendo se ele se refere a um arquivo de script autônomo ou a um arquivo de script que é inserido como um recurso em um assembly.The Auto value produces different results depending on whether it refers to a standalone script file or to a script file that is embedded as a resource in an assembly. Um arquivo de script autônomo é definido com a Path propriedade.A standalone script file is defined with the Path property. Uma referência de assembly deve ser acessada por meio das Name Assembly Propriedades e.An assembly reference must be accessed through the Name and Assembly properties. Os resultados para o Auto valor são os seguintes:The results for the Auto value are as follows:
Quando aplicado a um arquivo de script autônomo em que a Path propriedade é especificada, o Auto valor é equivalente a Release .When it is applied to a standalone script file where the Path property is specified, the Auto value is equivalent to Release.
Quando aplicado a uma referência de script em um assembly, Auto é equivalente a Inherit .When it is applied to a script reference in an assembly, Auto is equivalent to Inherit. Quando apenas Name é especificado, ele é usado para fazer referência ao script.When only Name is specified, it is used to reference the script. Quando Name e a Path propriedade são ambas especificadas, a Path propriedade é usada em vez de Name , mas o Auto valor ainda é equivalente a Inherit .When Name and the Path property are both specified, the Path property is used instead of Name, but the Auto value is still equivalent to Inherit.
Construtores
| ScriptReference() |
Inicializa uma nova instância da classe ScriptReference.Initializes a new instance of the ScriptReference class. |
| ScriptReference(String) |
Inicializa uma nova instância da classe ScriptReference usando um caminho especificado.Initializes a new instance of the ScriptReference class by using a specified path. |
| ScriptReference(String, String) |
Inicializa uma nova instância da classe ScriptReference usando um nome e um assembly especificados.Initializes a new instance of the ScriptReference class by using a specified name and assembly. |
Propriedades
| Assembly |
Obtém ou define o nome do assembly que contém o arquivo de script de cliente como um recurso inserido.Gets or sets the name of the assembly that contains the client script file as an embedded resource. |
| IgnoreScriptPath |
Obsoleto.
Obtém ou define um valor que indica se a propriedade ScriptPath está incluída na URL ao registrar um arquivo de script de cliente de um recurso.Gets or sets a value that indicates whether the ScriptPath property is included in the URL when you register a client script file from a resource. |
| Name |
Obtém ou define o nome do recurso inserido que contém o arquivo de script de cliente.Gets or sets the name of the embedded resource that contains the client script file. |
| NotifyScriptLoaded |
Obsoleto.
Obtém ou define um valor que indica se o objeto ScriptResourceHandler adiciona automaticamente o código no final do arquivo ECMAScript (JavaScript) para chamar o método NotifyScriptLoaded cliente da classe Sys.Application.Gets or sets a value that indicates whether the ScriptResourceHandler object automatically adds code at the end of the ECMAScript (JavaScript) file to call the client NotifyScriptLoaded method of the Sys.Application class. (Herdado de ScriptReferenceBase) |
| Path |
Obtém ou define o caminho do arquivo de script de cliente referenciado, relativo à página da Web.Gets or sets the path of the referenced client script file, relative to the Web page. (Herdado de ScriptReferenceBase) |
| ResourceUICultures |
Obtém ou define a lista delimitada por vírgulas das culturas de interface do usuário com suporte pela propriedade Path.Gets or sets a comma-delimited list of UI cultures that are supported by the Path property. (Herdado de ScriptReferenceBase) |
| ScriptMode |
Obtém ou define a versão do arquivo de script de cliente (versão ou depuração) a ser usado.Gets or sets the version of the client script file (release or debug) to use. (Herdado de ScriptReferenceBase) |
Métodos
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
| GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| GetUrl(ScriptManager, Boolean) |
Recupera a URL que é processada como o valor do atributo |
| IsAjaxFrameworkScript(ScriptManager) |
Determina se a referência de script é um script AJAX.Determines whether the script reference is an AJAX script. |
| IsAjaxFrameworkScript(ScriptManager) |
Determina se a referência de script especificada é um script AJAX do ASP.NET.Determines whether the specified script reference is an ASP.NET AJAX script. (Herdado de ScriptReferenceBase) |
| IsFromSystemWebExtensions() |
Obsoleto.
Indica se o script de composição contém uma referência a um script de estrutura AJAX ASP.NET.Indicates whether the composite script contains a reference to an ASP.NET AJAX framework script. |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| ToString() |
Retorna uma cadeia de caracteres que representa o valor da propriedade Name, a propriedade Path ou o nome do tipo.Returns a string that represents the value of the Name property, the Path property, or the type name. |