共用方式為


使用 AJAX 架構Microsoft ASP.NET 建立級聯下拉式清單的步驟

本文說明如何使用 ASP.NET AJAX 架構來建置串聯下拉式清單。

原始產品版本: .NET Framework 3.5
原始 KB 編號: 976156

簡介

注意

您必須安裝 .NET Framework 3.5,才能使用 ASP.NET AJAX 功能。 如果您想要將 ASP.NET AJAX 功能併入 .NET Framework 2.0 中,您必須安裝 ASP.NET 2.0 AJAX 延伸模組 1.0。

串聯下拉式清單是一系列的相依DropDownList控件,其中一個控件相依於父控件或上DropDownList一個DropDownList控件。 控件中的 DropDownList 專案會根據使用者從另一個 DropDownList 控件選取的專案來填入。 當父 DropDownList 控件的選取範圍變更時,網頁會呼叫 AJAX Web 服務,以擷取子 DropDownList 控件的值清單。 ASP.NET AJAX 架構可讓您使用用戶端腳本從瀏覽器呼叫 Web 服務(.asmx 檔案)。 因此,當您在父DropDownList控件的用戶端onchange事件中呼叫 Web 服務時,網頁只會部分重新整理以填入子DropDownList控件的專案。

注意

ASP.NET AJAX 控制件工具組提供控制項 CascadingDropDown 做為 ASP.NET AJAX 擴充器。 您可以使用 CascadingDropDown 控制項來建立級聯下拉式清單。 本文討論如何使用 ASP.NET 中的標準 DropDownList 控件與 ASP.NET AJAX 架構,以達成級聯下拉式函式。

建立串聯下拉式清單的步驟

  1. 在 Visual Studio 中建立 ASP.NET Web 服務應用程式。

    注意

    在提供的範例程式代碼中,C# 範例專案的專案名稱會 KB_CascadingDDL_CS。 Visual Basic .NET 範例專案的專案名稱KB_CascadingDDL_VB

  2. 將 AJAX Web Form 新增至專案。

    注意

    在範例程式代碼中,Web 窗體的檔名Default.aspx。 AJAX Web 服務名稱為 WebService

  3. 開啟 AJAX Web 服務的 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 Web 服務從用戶端腳本存取。 AJAX Web 服務類別必須 ScriptServiceAttribute 套用 屬性,而且從用戶端腳本呼叫的個別方法必須 WebMethodAttribute 套用 屬性。

  4. 開啟 Web 窗體的WebFormName.aspx檔案,然後變更 <asp:ScriptManager> 標記,如下所示:

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

    若要從 ASP.NET Web 窗體中的用戶端腳本呼叫 AJAX Web 服務,您必須先將控件新增 ScriptManager 至網頁。 然後,藉由將子專案新增 <asp:ServiceReference><asp:ScriptManager> 標記來參考 Web 服務。 在標記中<asp:ScriptManager>Path,將屬性設定為指向 Web 服務檔案。

    ServiceReference物件會指示 ASP.NET 2.0 AJAX 延伸模組產生 JavaScript Proxy 類別,以便從網頁中的用戶端腳本呼叫指定的 Web 服務。 Proxy 類別具有對應至 AJAX Web 服務中每個 Web 服務方法的方法。 網頁也包含 JavaScript Proxy 類別,這些類別會對應至做為 Web 服務方法輸入參數或傳回值的伺服器數據類型。 這些 Proxy 類別可讓您撰寫用戶端腳本,以初始化這些參數,並將其傳遞至 Web 服務方法呼叫。

  5. EnableEventValidationWebFormName.aspx檔案的原始程式碼中,將網頁的 屬性設定為 false,如下列範例所示。

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

    注意

    當您使用 Web 服務方法呼叫時,此步驟是避免回傳無效。

  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 Web 服務的 Web 服務方法。 將下列程式代碼複製並貼到 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 Web 服務的 Web 服務方法。 將下列程式代碼複製並貼到您在步驟 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>
    

    從腳本呼叫 Web 服務方法是異步的。 若要取得傳回值,或判斷要求何時傳回,您必須提供成功的回呼函式。 當要求成功完成時,會叫用回呼函式,並且包含來自 Web 服務方法呼叫的傳回值。 您也可以提供失敗的回呼函式來處理錯誤。 此外,您可以傳遞使用者內容資訊,以用於回呼函式。

    您可以使用下列格式,以 AJAX Web 服務呼叫 Web 服務方法:

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

    您可以提供從多個 Web 服務方法呼叫叫用的單一成功回呼函式。 若要讓函式區分不同的呼叫端,您可以將使用者內容資訊傳遞至 參數中的 函式。

  9. 組建專案。

參考資料

ASP.NET Ajax:增強互動性和回應性