Procedura per creare un elenco a discesa a cascata usando il framework AJAX di Microsoft ASP.NET

Questo articolo illustra come compilare un elenco a discesa a catena usando il framework AJAX ASP.NET.

Versione originale del prodotto: .NET Framework 3.5
Numero KB originale: 976156

Introduzione

Nota

È necessario che .NET Framework 3.5 sia installato per usare le funzionalità ASP.NET AJAX. Se si desidera incorporare ASP.NET funzionalità AJAX in .NET Framework 2.0, è necessario avere installato ASP.NET 2.0 AJAX Extensions 1.0.

Un elenco a discesa a cascata è una serie di controlli dipendenti DropDownList in cui un DropDownList controllo dipende dai controlli padre o precedenti DropDownList . Gli elementi nel DropDownList controllo vengono popolati in base a un elemento selezionato dall'utente da un altro DropDownList controllo. Quando viene modificata la selezione di un controllo padre DropDownList , la pagina Web chiama il servizio Web AJAX per recuperare l'elenco di valori per il controllo figlio DropDownList . Il framework ASP.NET AJAX consente di chiamare i servizi Web (file con estensione asmx) dal browser usando script client. Pertanto, quando si chiama il servizio Web nell'evento lato onchange client del controllo padre DropDownList , la pagina Web verrà aggiornata solo parzialmente per popolare gli elementi per il controllo figlio DropDownList .

Nota

ASP.NET AJAX Control Toolkit fornisce un CascadingDropDown controllo come estensione AJAX ASP.NET. È possibile usare il CascadingDropDown controllo per creare un elenco a discesa a cascata. Questo articolo illustra come usare il controllo standard DropDownList in ASP.NET insieme al framework AJAX ASP.NET per ottenere la funzione a discesa a cascata.

Passaggi per creare un elenco a discesa a cascata

  1. Creare un'applicazione del servizio Web ASP.NET in Visual Studio.

    Nota

    Nel codice di esempio fornito viene KB_CascadingDDL_CS il nome del progetto di esempio C#. Il nome del progetto di esempio .NET di Visual Basic è KB_CascadingDDL_VB.

  2. Aggiungere un Web Form AJAX al progetto.

    Nota

    Nel codice di esempio il nome del file del modulo Web viene Default.aspx. Il nome del servizio Web AJAX è WebService.

  3. Aprire il file WebServiceName.asmx per il servizio Web AJAX e quindi rimuovere il contrassegno di commento per la dichiarazione di classe come indicato di seguito.

    Visual Basic

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

    Oggetto visivo C#

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

    Nota

    Questo passaggio consente l'accesso al servizio Web AJAX dagli script sul lato client. A una classe del servizio Web AJAX deve essere applicato l'attributo ScriptServiceAttribute e ai singoli metodi che verranno chiamati dagli script sul lato client deve essere applicato l'attributo WebMethodAttribute .

  4. Aprire il file WebFormName.aspx del Web form e quindi modificare il <tag asp:ScriptManager> come indicato di seguito:

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

    Per abilitare la chiamata di un servizio Web AJAX dagli script sul lato client in un Web form ASP.NET, è necessario prima aggiungere un ScriptManager controllo alla pagina Web. Fare quindi riferimento al servizio Web aggiungendo un <asp:ServiceReference> elemento figlio al <asp:ScriptManager> tag . <asp:ScriptManager> Nel tag impostare l'attributo Path in modo che punti al file del servizio Web.

    L'oggetto ServiceReference indica ASP.NET estensioni AJAX 2.0 di generare una classe proxy JavaScript per chiamare il servizio Web specificato dagli script lato client nella pagina Web. La classe proxy dispone di metodi che corrispondono a ogni metodo del servizio Web nel servizio Web AJAX. La pagina Web contiene anche classi proxy JavaScript che corrispondono ai tipi di dati del server usati come parametri di input o valori restituiti per i metodi del servizio Web. Queste classi proxy consentono di scrivere script sul lato client che inizializzano questi parametri e di passarli alla chiamata al metodo del servizio Web.

  5. Impostare la EnableEventValidation proprietà della pagina Web su false nel codice sorgente del file WebFormName.aspx , come illustrato nell'esempio seguente.

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

    Nota

    Questo passaggio consente di evitare postback non validi quando si usano chiamate al metodo del servizio Web.

  6. Aggiungere il codice seguente nel <tag asp:ScriptManager> per generare i controlli ASP.NET necessari.

    <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. Creare metodi del servizio Web per il servizio Web AJAX. Copiare e incollare il codice seguente nel file 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
    

    Oggetto visivo 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. Chiamare i metodi del servizio Web per il servizio Web AJAX da script sul lato client. Copiare e incollare il codice seguente nel codice aggiunto nel passaggio 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>
    

    La chiamata di un metodo di servizio Web da uno script è asincrona. Per ottenere un valore restituito o per determinare quando la richiesta è stata restituita, è necessario fornire una funzione di callback completata. La funzione di callback viene richiamata al termine della richiesta e contiene il valore restituito dalla chiamata al metodo del servizio Web. È anche possibile fornire una funzione di callback non riuscita per gestire gli errori. Inoltre, è possibile passare le informazioni sul contesto utente da usare nelle funzioni di callback.

    È possibile chiamare un metodo del servizio Web in un servizio Web AJAX nel formato seguente:

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

    È possibile fornire una singola funzione di callback completata richiamata da più chiamate al metodo del servizio Web. Per consentire alla funzione di distinguere i diversi chiamanti, è possibile passare le informazioni sul contesto utente alla funzione nel parametro .

  9. Generare il progetto.

Riferimenti

ASP.NET Ajax: interattività e velocità di risposta migliorate