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 Extensions 1.0 がインストールされている必要があります。

カスケード ドロップダウン リストは、1 つのコントロールが親コントロールまたは以前DropDownListのコントロールに依存する一DropDownList連の依存DropDownListコントロールです。 コントロール内の DropDownList 項目は、ユーザーが別 DropDownList のコントロールから選択した項目に基づいて設定されます。 親 DropDownList コントロールの選択が変更されると、Web ページは AJAX Web サービスを呼び出して、子 DropDownList コントロールの値の一覧を取得します。 ASP.NET AJAX フレームワークを使用すると、クライアント スクリプトを使用してブラウザーから Web サービス (.asmx ファイル) を呼び出すことができます。 そのため、親DropDownListコントロールのクライアント側onchangeイベントで Web サービスを呼び出すと、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 フォームを追加します。

    注:

    サンプル コードでは、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 サービスを呼び出せるようにするには、まず Web ページにコントロールを ScriptManager 追加する必要があります。 次に、タグに子要素を <asp:ServiceReference> 追加して Web サービスを <asp:ScriptManager> 参照します。 タグで <asp:ScriptManager> 、 属性を Path Web サービス ファイルを指すように設定します。

    オブジェクトは ServiceReference 、2.0 AJAX 拡張機能 ASP.NET、指定された Web サービスを Web ページのクライアント側スクリプトから呼び出すための JavaScript プロキシ クラスを生成するように指示します。 プロキシ クラスには、AJAX Web サービスの各 Web サービス メソッドに対応するメソッドがあります。 Web ページには、Web サービス メソッドの入力パラメーターまたは戻り値として使用されるサーバー データ型に対応する JavaScript プロキシ クラスも含まれています。 これらのプロキシ クラスを使用すると、これらのパラメーターを初期化し、Web Service メソッド呼び出しに渡すクライアント側スクリプトを記述できます。

  5. EnableEventValidation次の例に示すように、WebFormName.aspx ファイルのソース コードで Web ページのプロパティを false に設定します。

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

    注:

    この手順では、Web Service メソッド呼び出しを使用するときに無効なポストバックを回避します。

  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 サービス メソッド呼び出しから呼び出される 1 つの成功したコールバック関数を指定できます。 関数が異なる呼び出し元を区別できるようにするには、パラメーター内の関数にユーザー コンテキスト情報を渡します。

  9. プロジェクトをビルドします。

関連情報

ASP.NET Ajax: 対話機能と応答性の強化