다음을 통해 공유


연습: 어셈블리에 JavaScript 파일을 리소스로 포함

업데이트: 2007년 11월

이 연습에서는 JavaScript 파일을 포함 리소스로 어셈블리에 포함합니다. 만든 어셈블리와 함께 배포해야 하는 클라이언트 스크립트 구성 요소가 있을 경우 JavaScript 파일을 포함합니다. 예를 들어 JavaScript 파일을 사용하여 ASP.NET의 AJAX 기능을 구현하는 데 사용하는 사용자 지정 ASP.NET 서버 컨트롤을 만들 수 있습니다. 이 경우 어셈블리에 JavaScript 파일을 포함한 다음 어셈블리를 등록하는 웹 응용 프로그램에서 이 파일을 참조할 수 있습니다.

사전 요구 사항

이 연습의 절차를 구현하려면 다음이 필요합니다.

  • Microsoft Visual Studio 2005.

    참고:

    Visual Web Developer Express Edition에서는 이 연습에 필요한 클래스 라이브러리 프로젝트를 만들 수 없으므로 Visual Web Developer 2005 Express Edition을 사용할 수 없습니다.

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

    이 코드에는 UpdatePanel 컨트롤 주위에 색이 지정된 테두리를 일시적으로 표시하는 JavaScript 기능이 포함됩니다.

  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 컨트롤 주위에 표시되는 테두리를 사용자 지정하기 위한 속성이 포함됩니다. 또한 이 코드는 웹 페이지에서 사용할 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 파일은 솔루션 탐색기의 My Project 노드에 있습니다. My Project 노드에 파일이 없으면 프로젝트 메뉴에서 모든 파일 표시를 클릭합니다. AssemblyInfo.cs 파일은 솔루션 탐색기의 속성 노드에 있습니다.

    WebResource 정의에는 어셈블리의 기본 네임스페이스와 .js 파일 이름이 포함되어 있어야 합니다.

  9. 프로젝트를 빌드합니다.

    컴파일이 끝나면 SampleControl.dll이라는 어셈블리가 생깁니다. UpdatePanelAnimation.js 파일의 JavaScript 코드가 이 어셈블리에 리소스로 포함되어 있습니다.

포함 스크립트 파일 참조

이제 웹 응용 프로그램에서 포함 스크립트 파일을 참조할 수 있습니다.

참고:

클래스 라이브러리 프로젝트와 웹 사이트를 동일한 Visual Studio 솔루션에서 만들 수도 있지만 이 연습에서는 이렇게 하는 것으로 가정하지 않습니다. 프로젝트를 별도의 솔루션에서 만들면 컨트롤 개발자와 페이지 개발자가 따로 작업하는 방식을 모방할 수 있습니다. 그러나 편의상 두 프로젝트를 같은 솔루션에서 만들고 이 연습의 절차에 맞게 약간 조정할 수 있습니다.

포함 스크립트 파일을 참조하려면

  1. Visual Studio에서 새 AJAX 사용 웹 사이트를 만듭니다.

  2. 웹 사이트의 루트 디렉터리에서 Bin 폴더를 만듭니다.

  3. 클래스 라이브러리 프로젝트의 Bin\Debug 또는 Bin\Release 디렉터리에서 SampleControl.dll 파일을 웹 사이트의 Bin 폴더로 복사합니다.

    참고:

    동일한 Visual Studio 솔루션에서 클래스 라이브러리 프로젝트와 웹 사이트를 만든 경우 클래스 라이브러리 프로젝트와 웹 사이트 사이의 참조를 추가할 수 있습니다. 자세한 내용은 방법: 웹 사이트의 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>
    

    이 코드에는 이전 절차에서 만든 .js 파일의 이름과 어셈블리를 참조하는 ScriptReference 컨트롤이 포함됩니다. .js 파일의 이름에는 어셈블리의 기본 네임스페이스를 참조하는 접두사가 포함됩니다.

  5. 프로젝트를 실행하고 페이지에서 달력의 날짜를 클릭합니다.

    달력의 날짜를 클릭할 때마다 UpdatePanel 컨트롤 주위에 녹색 테두리가 표시됩니다.

검토

이 연습에서는 JavaScript 파일을 포함 리소스로 어셈블리에 포함하는 방법에 대해 설명했습니다. 포함 스크립트 파일은 해당 어셈블리를 포함하는 웹 응용 프로그램에서 액세스할 수 있습니다.

다음 단계에서는 클라이언트 스크립트에서 사용할 지역화된 리소스를 어셈블리에 포함하는 방법에 대해 알아 봅니다. 자세한 내용은 연습: JavaScript 파일에 지역화된 리소스 포함을 참조하십시오.

참고 항목

작업

연습: JavaScript 파일에 지역화된 리소스 추가

개념

Microsoft AJAX 라이브러리를 사용하여 사용자 지정 클라이언트 스크립트 만들기