Microsoft ASP.NET AJAX 프레임워크를 사용하여 계단식 드롭다운 목록을 만드는 단계

이 문서에서는 ASP.NET AJAX 프레임워크를 사용하여 계단식 드롭다운 목록을 빌드하는 방법을 보여줍니다.

원래 제품 버전: .NET Framework 3.5
원본 KB 번호: 976156

소개

참고

ASP.NET AJAX 기능을 사용하려면 .NET Framework 3.5가 설치되어 있어야 합니다. .NET Framework 2.0에 ASP.NET AJAX 기능을 통합하려면 ASP.NET 2.0 AJAX 확장 1.0이 설치되어 있어야 합니다.

연속 드롭다운 목록은 하나의 DropDownList 컨트롤이 부모 또는 이전 DropDownList 컨트롤에 종속되는 일련의 종속 DropDownList 컨트롤입니다. 컨트롤의 DropDownList 항목은 다른 DropDownList 컨트롤에서 사용자가 선택한 항목에 따라 채워집니다. 부모 DropDownList 컨트롤의 선택이 변경되면 웹 페이지에서 AJAX 웹 서비스를 호출하여 자식 DropDownList 컨트롤에 대한 값 목록을 검색합니다. ASP.NET AJAX 프레임워크를 사용하면 클라이언트 스크립트를 사용하여 브라우저에서 웹 서비스(.asmx 파일)를 호출할 수 있습니다. 따라서 부모 DropDownList 컨트롤의 클라이언트 쪽 onchange 이벤트에서 웹 서비스를 호출하면 자식 DropDownList 컨트롤에 대한 항목을 채우기 위해 웹 페이지가 부분적으로만 새로 고쳐집니다.

참고

ASP.NET AJAX 컨트롤 도구 키트는 ASP.NET AJAX 확장자로 컨트롤을 제공합니다 CascadingDropDown . 컨트롤을 CascadingDropDown 사용하여 계단식 드롭다운 목록을 만들 수 있습니다. 이 문서에서는 ASP.NET 표준 DropDownList 컨트롤을 ASP.NET AJAX 프레임워크와 함께 사용하여 연속 드롭다운 함수를 구현하는 방법을 설명합니다.

계단식 드롭다운 목록을 만드는 단계

  1. Visual Studio에서 ASP.NET 웹 서비스 애플리케이션을 만듭니다.

    참고

    제공된 샘플 코드에서 C# 샘플 프로젝트의 프로젝트 이름은 KB_CascadingDDL_CS. Visual Basic .NET 샘플 프로젝트의 프로젝트 이름은 KB_CascadingDDL_VB.

  2. 프로젝트에 AJAX 웹 양식을 추가합니다.

    참고

    샘플 코드에서 웹 양식의 파일 이름은 Default.aspx. AJAX 웹 서비스 이름은 WebService입니다.

  3. AJAX 웹 서비스에 대한 WebServiceName.asmx 파일을 열고 다음과 같이 클래스 선언에 대한 주석 표시를 제거합니다.

    Visual Basic

    <System.Web.Script.Services.ScriptService()>
    Public Class WebService
    

    Visual C#

    [System.Web.Script.Services.ScriptService]
    public class WebService : System.Web.Services.WebService
    

    참고

    이 단계를 사용하면 클라이언트 쪽 스크립트에서 AJAX 웹 서비스에 액세스할 수 있습니다. AJAX 웹 서비스 클래스에는 특성이 ScriptServiceAttribute 적용되어 있어야 하며 클라이언트 쪽 스크립트에서 호출되는 개별 메서드에는 특성이 WebMethodAttribute 적용되어 있어야 합니다.

  4. 웹 양식의 WebFormName.aspx 파일을 열고 asp:ScriptManager> 태그를 다음과 같이 변경<합니다.

    <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Services>
            <asp:ServiceReference Path="~/WebServiceName.asmx" />
        </Services>
    </asp:ScriptManager>
    

    ASP.NET 웹 양식의 클라이언트 쪽 스크립트에서 AJAX 웹 서비스를 호출할 수 있도록 하려면 먼저 웹 페이지에 컨트롤을 ScriptManager 추가해야 합니다. 그런 다음 태그에 자식 요소를 추가하여 <asp:ServiceReference> 웹 서비스를 참조합니다 <asp:ScriptManager> . 태그에서 <asp:ScriptManager> 특성을 웹 서비스 파일을 가리키도록 설정합니다 Path .

    개체는 ServiceReference ASP.NET 2.0 AJAX 확장에 웹 페이지의 클라이언트 쪽 스크립트에서 지정된 웹 서비스를 호출하기 위한 JavaScript 프록시 클래스를 생성하도록 지시합니다. 프록시 클래스에는 AJAX 웹 서비스의 각 웹 서비스 메서드에 해당하는 메서드가 있습니다. 웹 페이지에는 입력 매개 변수로 사용되거나 웹 서비스 메서드의 반환 값으로 사용되는 서버 데이터 형식에 해당하는 JavaScript 프록시 클래스도 포함되어 있습니다. 이러한 프록시 클래스를 사용하면 이러한 매개 변수를 초기화하고 웹 서비스 메서드 호출에 전달하는 클라이언트 쪽 스크립트를 작성할 수 있습니다.

  5. EnableEventValidation 다음 예제와 같이 WebFormName.aspx 파일의 소스 코드에서 웹 페이지의 속성을 false로 설정합니다.

    <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="KB_CascadingDDL_VB._Default"
     EnableEventValidation="false" %>
    

    참고

    이 단계는 웹 서비스 메서드 호출을 사용할 때 잘못된 포스트백을 방지하기 위한 것입니다.

  6. asp:ScriptManager> 태그 아래에 <다음 코드를 추가하여 필요한 ASP.NET 컨트롤을 생성합니다.

    <table>
        <tr>
            <td>
                Make:
            </td>
            <td>
                <asp:DropDownList ID="ddlMake" Width="200" runat="server" AutoPostBack="false" onchange="ddl_changed(this)" />
            </td>
        </tr>
        <tr>
            <td>
                Model:
            </td>
            <td>
                <asp:DropDownList ID="ddlModel" Width="200" runat="server" AutoPostBack="false" onchange="ddl_changed(this)" />
            </td>
        </tr>
        <tr>
            <td>
                Color:
            </td>
            <td>
                <asp:DropDownList ID="ddlColor" Width="200" runat="server" AutoPostBack="false" onchange="DisplayResult()" />
            </td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btnReset" runat="server" Text="Reset" />
            </td>
        </tr>
    </table>
    <a id="aResult" />
    
  7. AJAX 웹 서비스에 대한 웹 서비스 메서드를 만듭니다. 다음 코드를 복사하여 WebServiceName.asmx 파일에 붙여넣습니다.

    Visual Basic

    Imports System.Web.Services
    Imports System.Web.Services.Protocols
    Imports System.ComponentModel
    
    ' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    <System.Web.Script.Services.ScriptService()> _
    <System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
    <System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
    <ToolboxItem(False)> _
    Public Class WebService
        Inherits System.Web.Services.WebService
    
        <WebMethod()> _
        Public Function GetMakeValue() As String()
            Return New String() {"Please select", "Ford", "Dodge"}
        End Function
    
        <WebMethod()> _
        Public Function GetChildValue(ByVal parentID As String, ByVal parentValue As String) As String()
            If parentValue = "Please select" Then
                Return Nothing
            End If
    
            Dim values As String()
            If parentID = "ddlMake" Then
                If parentValue = "Ford" Then
                    values = New String() {"Please select", "Explorer", "F150", "Mustang"}
                ElseIf parentValue = "Dodge" Then
                    values = New String() {"Please select", "Durango", "Dakota", "Viper"}
                Else
                    Return New String() {"Invalid Make value!"}
                End If
            ElseIf parentID = "ddlModel" Then
                Select Case parentValue
                    Case "Explorer", "Dakota", "Viper"
                        values = New String() {"Please select", "Black", "Green", "Yellow"}
                    Case "Durango", "F150", "Mustang"
                        values = New String() {"Please select", "White", "Red", "Blue"}
                    Case Else
                        values = New String() {"Invalid Model value!"}
                End Select
            Else
                Return New String() {"Invalid Category value!"}
            End If
            Return values
        End Function
    End Class
    

    Visual C#

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    
    namespace KB_CascadingDDL_CS
    {
        /// <summary>
        /// Summary description for WebService
        /// </summary>
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
        [System.Web.Script.Services.ScriptService]
        public class WebService : System.Web.Services.WebService
        {
            [WebMethod()]
            public string[] GetMakeValue()
            {
                return new string[] { "Please select", "Ford", "Dodge" };
            }
    
            [WebMethod()]
            public string[] GetChildValue(string parentID, string parentValue)
            {
                if (parentValue == "Please select")
                {
                    return null;
                }
    
                string[] values;
                if (parentID == "ddlMake")
                {
                    if (parentValue == "Ford")
                    {
                        values = new string[] { "Please select", "Explorer", "F150", "Mustang" };
                    }
                    else if (parentValue == "Dodge")
                    {
                        values = new string[] { "Please select", "Durango", "Dakota", "Viper" };
                    }
                    else
                    {
                        return new string[] { "Invalid Make value!" };
                    }
                }
                else if (parentID == "ddlModel")
                {
                    switch (parentValue)
                    {
                        case "Explorer":
                        case "Dakota":
                        case "Viper":
                            values = new string[] { "Please select", "Black", "Green", "Yellow" };
                            break;
                        case "Durango":
                        case "F150":
                        case "Mustang":
                            values = new string[] { "Please select", "White", "Red", "Blue" };
                            break;
                        default:
                            values = new string[] { "Invalid Model value!" };
                            break;
                    }
                }
                else
                {
                    return new string[] { "Invalid Category value!" };
                }
                return values;
            }
        }
    }
    
  8. 클라이언트 쪽 스크립트에서 AJAX 웹 서비스에 대한 웹 서비스 메서드를 호출합니다. 6단계에서 추가한 코드 아래에 다음 코드를 복사하여 붙여넣습니다.

    <script type="text/javascript">
        function pageLoad()
        {
            // call a Web service method with no parameters and the user context.
            KB_CascadingDDL_VB.WebService.GetMakeValue(SucceededCallbackWithContext, FailedCallback, "fillMake");
        }
    
        // Event handler for ddlMake and ddlModel.
        // This function calls a Web service method
        // passing simple type parameters and the user context.
        function ddl_changed(sender)
        {
            // This initiates the call to the server-side method in your code-behind
            // The parameters are as follows:
            // 1st : Specify all the parameters expected by your code-behind method
            //      (in this case there are 2: parentControl's ID, parentControl's selected text)
            // 2nd : Specify a callback method when the call succeeds
            // 3rd : Specify a callback method when the call fails(optional)
            // 4th : Specify a user context object (option - not shown)
            //      (in this case we need to assign the parentControl's ID as the user context)
            KB_CascadingDDL_VB.WebService.GetChildValue(sender.id, sender[sender.selectedIndex].text,
            SucceededCallbackWithContext, FailedCallback, sender.id);
        }
    
        // This is the callback function called if the
        // Web service succeeded. It accepts the result
        // object, the user context, and the method name as
        // parameters.
        function SucceededCallbackWithContext(result, userContext) {
    
            if (userContext == "fillMake") {
                //fill the Make
                var ddl = $get('ddlMake');
            } else if (userContext == "ddlMake") {
                // fill the Model
                var ddl = $get('ddlModel');
                $get('ddlColor').options.length = 0;
            } else if (userContext == "ddlModel") {
                // fill the Color
                var ddl = $get('ddlColor');
            }
            // clear the options
            ddl.options.length = 0;
            if (result)
            {
                var i = 0;
                for (var item in result)
                {
                    // item is the key, result[item] is the value
                    ddl.options.add(new Option(result[item], item));
                    i++;
                }
            } else {
                alert("Invalid! Please reset the selection!");
                $get(userContext).focus();
            }
        }
    
        // This is the callback function called if the
        // Web service failed. It accepts the error object
        // as a parameter.
        function FailedCallback(error)
        {
            if (error)
            {
                alert(error.get_message());
            }
            else
                alert("An unexpeceted error occurred");
        }
    
        //This the function to show the three DropDownLists'selection
        function DisplayResult()
        {
            $get("aResult").innerHTML = "You have selected a " +
            $get("ddlMake")[$get("ddlMake").selectedIndex].text + "," +
            $get("ddlModel")[$get("ddlModel").selectedIndex].text + "," +
            $get("ddlColor")[$get("ddlColor").selectedIndex].text + " car!";
        }
    </script>
    

    스크립트에서 웹 서비스 메서드를 호출하는 것은 비동기적입니다. 반환 값을 가져오거나 요청이 반환된 시기를 확인하려면 성공한 콜백 함수를 제공해야 합니다. 콜백 함수는 요청이 성공적으로 완료되면 호출되며 웹 서비스 메서드 호출의 반환 값이 포함됩니다. 실패한 콜백 함수를 제공하여 오류를 처리할 수도 있습니다. 또한 콜백 함수에서 사용할 사용자 컨텍스트 정보를 전달할 수 있습니다.

    AJAX 웹 서비스에서 웹 서비스 메서드를 다음 형식으로 호출할 수 있습니다.

    theServiceNameSpace.WebServiceName.ServiceMethodName(parameters, SucceededCallbackFunctionName, FailedCallbackFunctionName, userContextString);
    

    여러 웹 서비스 메서드 호출에서 호출되는 단일 성공 콜백 함수를 제공할 수 있습니다. 함수가 다른 호출자를 구분할 수 있도록 하려면 매개 변수의 함수에 사용자 컨텍스트 정보를 전달할 수 있습니다.

  9. 프로젝트를 만듭니다.

참조

ASP.NET Ajax: 향상된 대화형 대화형 및 응답성