逐步解說:嵌入 JavaScript 檔做為組件中的資源

更新:2007 年 11 月

在這個逐步解說中,您將在組件中加入 JavaScript 檔做為內嵌資源。當您的用戶端指令碼元件必須隨著您已建立的組件一起散發時,您可以嵌入 JavaScript 檔。例如,您可能建立自訂 ASP.NET 伺服器控制項,這個控制項使用 JavaScript 檔實作 ASP.NET 的 AJAX 功能。您可以在組件中嵌入 JavaScript 檔,註冊該組件的 Web 應用程式就能參考這些檔案。

必要條件

若要實作本逐步解說中的程序,您需要:

  • Microsoft Visual Studio 2005.

    注意事項:

    您不能使用 Visual Web Developer 2005 Express 版,因為 Visual Web Developer Express 版無法讓您建立逐步解說中所需的類別庫專案。

建立包含內嵌 JavaScript 檔的組件

一開始將建立一個檔案,這個檔案包含您要嵌入組件中的 JavaScript 程式碼。

將用戶端指令碼檔案嵌入組件中

  1. 在 Visual Studio 中,建立新的類別庫專案,命名為 SampleControl。

  2. 將 System.Web、System.Drawing 和 System.Web.Extensions 組件的參考加入至專案。

  3. 將名為 UpdatePanelAnimation.js 的新 JScript 檔加入至專案。

  4. 將下列程式碼加入至 UpdatePanelAnimation.js 檔案:

    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);
        }
    }
    
    
    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);
        }
    }
    
    

    程式碼包含 JavaScript 函式,這個函式會在 UpdatePanel 控制項周圍暫時顯示彩色框線。

  5. 在 UpdatePanelAnimation.js 檔案的 [屬性] 視窗中,將 [建置動作] 設定為 [內嵌資源]。

  6. 將名為 CustomControl 的類別檔加入至專案。

  7. 使用下列程式碼取代 CustomControl 檔案中的任何程式碼:

    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
    
    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);
                }
            }
        }
    }
    

    這個類別包含屬性,可自訂 UpdatePanel 周圍顯示的框線。這段程式碼也會註冊可在 Web 網頁中使用的 JavaScript 程式碼。這段程式碼會為 Sys.Application 物件的 load 事件建立處理常式。處理網頁局部更新時會呼叫 UpdatePanelAnimation.js 檔案中的 animate 函式。

  8. 將下列行加入至 AssemblyInfo 檔案。

    <Assembly: System.Web.UI.WebResource("SampleControl.UpdatePanelAnimation.js", "application/x-javascript")> 
    
    [assembly: System.Web.UI.WebResource("SampleControl.UpdatePanelAnimation.js", "application/x-javascript")]
    
    注意事項:

    AssemblyInfo.vb 檔案位於 [方案總管] 的 [我的專案] 節點內。如果您沒有在 [我的專案] 節點內看到任何檔案,請按一下 [專案] 功能表上的 [顯示所有檔案]。AssemblyInfo.cs 檔案位於 [方案總管] 的 [屬性] 節點內。

    WebResource 定義必須包含組件的預設命名空間以及 .js 檔案的名稱。

  9. 建置專案。

    編譯完成時,您會得到名為 SampleControl.dll 的組件。UpdatePanelAnimation.js 檔案中的 JavaScript 程式碼會內嵌為此組件中的資源。

參考內嵌的指令碼檔案

您現在可以在 Web 應用程式中參考內嵌的指令碼檔案。

注意事項:

雖然您可以在相同的 Visual Studio 方案中建立類別庫專案與網站,但此逐步解說假設您不會這樣做。在不同的方案建立專案可模擬控制項開發人員與網頁開發人員獨立工作的情況。不過,為了方便起見,您可以在相同的方案中建立兩個專案,並稍微調整此逐步解說中的程序。

若要參考內嵌的指令碼檔案

  1. 在 Visual Studio 中,建立具備 AJAX 能力的新網站。

  2. 在網站的根目錄中建立 Bin 資料夾。

  3. 將 SampleControl.dll 從類別庫專案的 Bin\Debug 或 Bin\Release 目錄複製到網站的 Bin 資料夾。

    注意事項:

    若在相同的 Visual Studio 方案中建立類別庫專案與網站,您可以從類別程式庫專案加入參考至網站。如需詳細資訊,請參閱 HOW TO:加入參考至網站中的 Visual Studio 專案

  4. 使用下列程式碼取代 Default.aspx 檔案中的程式碼:

    <%@ 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" >
        <title>ScriptReference</title>
    </head>
    <body>
        <form id="form1" >
            <div>
                <asp:ScriptManager ID="ScriptManager1" 
                                     EnablePartialRendering="True"
                                     >
                 <Scripts>
                    <asp:ScriptReference Assembly="SampleControl" Name="SampleControl.UpdatePanelAnimation.js" />
                 </Scripts>
                </asp:ScriptManager>
    
    
                <Samples:UpdatePanelAnimationWithClientResource 
                         ID="UpdatePanelAnimator1"
                         BorderColor="Green"
                         Animate="true"
                         UpdatePanelID="UpdatePanel1"
                          >
                </Samples:UpdatePanelAnimationWithClientResource>
                <asp:UpdatePanel ID="UpdatePanel1" 
                                   UpdateMode="Conditional"
                                   >
                    <ContentTemplate>
                        <asp:Calendar ID="Calendar2" 
                                      >
                        </asp:Calendar>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>
        </form>
    </body>
    </html>
    
    <%@ 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 >
    
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head >
        <title>ScriptReference</title>
    </head>
    <body>
        <form id="form1" >
            <div>
                <asp:ScriptManager ID="ScriptManager1" 
                                     EnablePartialRendering="True"
                                     >
                 <Scripts>
                    <asp:ScriptReference Assembly="SampleControl" Name="SampleControl.UpdatePanelAnimation.js" />
                 </Scripts>
                </asp:ScriptManager>
    
    
                <Samples:UpdatePanelAnimationWithClientResource 
                         ID="UpdatePanelAnimator1"
                         BorderColor="Green"
                         Animate="true"
                         UpdatePanelID="UpdatePanel1"
                          >
                </Samples:UpdatePanelAnimationWithClientResource>
                <asp:UpdatePanel ID="UpdatePanel1" 
                                   UpdateMode="Conditional"
                                   >
                    <ContentTemplate>
                        <asp:Calendar ID="Calendar2" 
                                      >
                        </asp:Calendar>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>
        </form>
    </body>
    </html>
    

    這段程式碼包含 ScriptReference 控制項,這個控制項參考您在前一程序中建立的組件和 .js 檔的名稱。.js 檔的名稱包含前置詞,這個前置詞參考組件的預設命名空間。

  5. 執行專案,並在網頁中按一下月曆中的日期。

    每次按一下月曆中的日期時,UpdatePanel 控制項周圍會出現綠色框線。

檢閱

這個逐步解說顯示如何嵌入 JavaScript 檔做為組件中的資源。從包含組件的 Web 應用程式中,可以存取內嵌的指令碼檔案。

下一個步驟是學習如何將當地語系化資源嵌入組件中,供用戶端指令碼使用。如需詳細資訊,請參閱逐步解說:嵌入已當地語系化的資源供 JavaScript 檔使用

請參閱

工作

逐步解說:將已當地語系化的資源加入至 JavaScript 檔

概念

使用 Microsoft AJAX Library 建立自訂用戶端指令碼