IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

ASP.NET Ajax Discussion :

Explication passage tutoriel CascadingDropdown


Sujet :

ASP.NET Ajax

  1. #1
    Membre actif
    Profil pro
    Inscrit en
    Avril 2008
    Messages
    526
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2008
    Messages : 526
    Points : 224
    Points
    224
    Par défaut Explication passage tutoriel CascadingDropdown
    Bonjour,

    J'ai étudié le tutoriel suivant http://dotnet.developpez.com/ajax/aj...with-database/ pour appliquer le contrôle CascadingDropdown sur mes deux listes déroulantes.

    Par contre, j'ai un petit souci de compréhension au niveau d'un passage :

    if (!kv.ContainsKey("Vendor") || !Int32.TryParse(kv["Vendor"],out VendorID))
    {
    throw new ArgumentException("Couldn't find vendor.");
    };
    Je ne comprend pas à quoi correspond l'élément kv car il n'est définit nul part ailleurs et donc n'est pas reconnu.

    Est-ce que quelqu'un saurait m'éclairer ?

    Merci.

  2. #2
    Membre du Club
    Inscrit en
    Juillet 2008
    Messages
    70
    Détails du profil
    Informations forums :
    Inscription : Juillet 2008
    Messages : 70
    Points : 54
    Points
    54
    Par défaut
    Hey,

    l'élément kv est un objet de type StringDictionary à définir juste avant comme ceci.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
    En gros tu dois coder comme ceci:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    public CascadingDropDownNameValue[] GetQuelqueChose(string knownCategoryValues, string category)
            {
     
                int VendorID;
                StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
                if (!kv.ContainsKey("Vendor") || !Int32.TryParse(kv["Vendor"], out VendorID))
                {
                    throw new ArgumentException("Couldn't find Vendor.");
                }; [...]
    Après le reste du tuto est complet.

  3. #3
    Membre actif
    Profil pro
    Inscrit en
    Avril 2008
    Messages
    526
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2008
    Messages : 526
    Points : 224
    Points
    224
    Par défaut
    Ok merci pour ta réponse.

    Par contre, je rencontre le message d'erreur [Method error 500] sur ma première liste déroulante.
    En cherchant sur internet, j'ai vu que plusieurs personnes avaient rencontré le problème mais j'ai testé plusieurs choses et je n'ai pas résolu mon problème.

    Voici mon code de ma page .asmx.cs :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    using System.Web.Script.Services;
    using AjaxControlToolkit;
    using System;
    using System.Web;
    using System.Web.Services;
    using System.Web.Services.Protocols;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Data.SqlClient;
     
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.Web.Script.Services.ScriptService()]
     
     
    public class ListesAuthentification : System.Web.Services.WebService
    {
        public CascadingDropDownNameValue[] GetSites(string knownCategoryValues, string category)
        {
            SqlConnection conn = new SqlConnection(@"data source=JF\PRO; initial catalog=BaseExemples; integrated security=true");
            conn.Open();
            SqlCommand comm = new SqlCommand("SELECT Code,Libellé FROM Site", conn);
            SqlDataReader dr = comm.ExecuteReader();
            List<CascadingDropDownNameValue> l = new List<CascadingDropDownNameValue>();
            while (dr.Read())
            {
                l.Add(new CascadingDropDownNameValue(dr["Libellé"].ToString(), dr["Code"].ToString()));
            }
            conn.Close();
            return l.ToArray();
        }
     
        [WebMethod]
        public CascadingDropDownNameValue[] GetNoms(string knownCategoryValues, string category)
        {
            int Code;
            CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
     
            StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
            if (!kv.ContainsKey("Sites") || !Int32.TryParse(kv["Sites"], out Code))
            {
                throw new ArgumentException("Pas de site");
            };
     
            SqlConnection conn = new SqlConnection(@"data source=JF\PRODOQ; initial catalog=BaseExemples; integrated security=true");
            conn.Open();
            SqlCommand comm = new SqlCommand("SELECT Code,Nom,Prénom FROM Site,AuthProdoq WHERE Code=@Code AND Site.code=AuthProdoq.Code", conn);
            comm.Parameters.AddWithValue("@Code", Code);
            SqlDataReader dr = comm.ExecuteReader();
            List<CascadingDropDownNameValue> l = new List<CascadingDropDownNameValue>();
            while (dr.Read())
            {
                l.Add(new CascadingDropDownNameValue(dr["Nom"].ToString() + " " + dr["Prénom"].ToString(), dr["Code"].ToString()));
            }
     
            conn.Close();
            return l.ToArray();
        }
     
     
    }//Fin de la classe
    Est-ce que quelqu'un saurait comment corriger le problème ?

    Merci.

  4. #4
    Membre du Club
    Inscrit en
    Juillet 2008
    Messages
    70
    Détails du profil
    Informations forums :
    Inscription : Juillet 2008
    Messages : 70
    Points : 54
    Points
    54
    Par défaut
    Je crois qu'on l'a tous plus ou moins rencontré à un moment ou un autre celui là.

    Cela vient soit de ta source (requête ou appel de ta chaine de connexion qui n'est pas bonne)
    soit (cas le plus courant) de ta déclaration du web service dans ta page .aspx.
    tu as surement dû mettre ceci
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    <asp:ScriptManager ID="asm" runat="server" />
    et cependant tu dois utiliser la dernière version de AjaxControlToolKit qui demande ceci:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    <ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="asm" />
    Remplace la première par la seconde et tiens nous au courant.

  5. #5
    Membre actif
    Profil pro
    Inscrit en
    Avril 2008
    Messages
    526
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2008
    Messages : 526
    Points : 224
    Points
    224
    Par défaut
    Non j'utilise bien la bonne déclaration :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"> </asp:ToolkitScriptManager>
    Je vais regarder au niveau de la requête mais c'est bizarre car ma chaine de connexion marche bien pour d'autres requêtes ?

  6. #6
    Membre actif
    Profil pro
    Inscrit en
    Avril 2008
    Messages
    526
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2008
    Messages : 526
    Points : 224
    Points
    224
    Par défaut
    A moins que ce soit dans la déclaration de mes listes qu'il y a un problème où un manque :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    <asp:DropDownList ID="ListeSites" runat="server" Width="165px"  ></asp:DropDownList>
    <asp:DropDownList ID="ListeNoms" runat="server" Width="165px" ></asp:DropDownList>
    <%-- Remplissage des listes déroulantes --%>
             <asp:CascadingDropDown ID="CascadingDropDownSites" runat="server" ServicePath="~/ListesAuthentification.asmx" ServiceMethod="GetSites" TargetControlID="ListeSites" Category="Sites" PromptText="Veuillez choisir un site">
            </asp:CascadingDropDown>
     
            <asp:CascadingDropDown ID="CascadingDropDownNoms" runat="server" ServicePath="~/ListesAuthentification.asmx" ServiceMethod="GetNoms" TargetControlID="ListeNoms" ParentControlID="ListeSites" Category="Noms" PromptText="Veuillez choisir un nom">
            </asp:CascadingDropDown>

  7. #7
    Membre du Club
    Inscrit en
    Juillet 2008
    Messages
    70
    Détails du profil
    Informations forums :
    Inscription : Juillet 2008
    Messages : 70
    Points : 54
    Points
    54
    Par défaut
    J'avais pas vu cette ligne dans ton asmx
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    [System.Web.Script.Services.ScriptService()]
    Je l'ai retiré de mon coté et ca marche, je n'ai plus eu l'erreur 500 après ça.

  8. #8
    Membre actif
    Profil pro
    Inscrit en
    Avril 2008
    Messages
    526
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2008
    Messages : 526
    Points : 224
    Points
    224
    Par défaut
    Non, cela ne change rien ?
    Pas facile de trouver le problème.

  9. #9
    Membre du Club
    Inscrit en
    Juillet 2008
    Messages
    70
    Détails du profil
    Informations forums :
    Inscription : Juillet 2008
    Messages : 70
    Points : 54
    Points
    54
    Par défaut
    Bon alors en vrac, les solutions que j'ai trouvé lorsque j'ai rencontré l'erreur 500
    1 - dans ta page aspx, mettre enableEventValidation="false" dans
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    <%@ Page Language="C#"  enableEventValidation="false" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
    2 - Si tu n'as pas modifié ton code depuis, il te manque un [WebMethod] avant ta classe
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    public CascadingDropDownNameValue[] GetSites(string knownCategoryValues, string category)
    3 - je nommerai le tag de tes contrôles AJAX autrement que "asp" déjà utilisé par les contrôles standard. (même si cela ne doit pas jouer)


    Je n'ai pas vu d'erreur dans ton code.

  10. #10
    Membre actif
    Profil pro
    Inscrit en
    Avril 2008
    Messages
    526
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2008
    Messages : 526
    Points : 224
    Points
    224
    Par défaut
    Même avec tout ça c'est pareil.

    Ce qui est bizarre, c'est que le message apparait déja sur la première liste alors que la requête est toute simple.

  11. #11
    Membre du Club
    Inscrit en
    Juillet 2008
    Messages
    70
    Détails du profil
    Informations forums :
    Inscription : Juillet 2008
    Messages : 70
    Points : 54
    Points
    54
    Par défaut
    je vois un @ dans ta chaine de connexion, c'est normale ??
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    SqlConnection conn = new SqlConnection(@"data source=JF\PRO; initial catalog=BaseExemples; integrated security=true");
    Elle y est dans tes autres appels ailleurs dans ton code ?

  12. #12
    Membre actif
    Profil pro
    Inscrit en
    Avril 2008
    Messages
    526
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2008
    Messages : 526
    Points : 224
    Points
    224
    Par défaut
    Bon après avoir tout essayé, rien à faire. Je met le code de mes pages où cas où quelqu'un verrait le problème :

    Page test.aspx :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="ProDoQ_Design.test" EnableEventValidation="false" %>
     
     
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
     
    <!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" runat="server">
        <title>test</title>
        <link href="Style.css" rel="stylesheet" type="text/css" />
        <link href="StyleDetection.css" rel="stylesheet" type="text/css" />
     
    </head>
     
    <body>
        <form id="form1" runat="server">
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </asp:ToolkitScriptManager>  
           <table border="0" cellpadding="2" cellspacing="0" width="500">    <tr>     
              <td width="100">        
                  <b>Select Category :</b></td>    
                      <td>           
                       <asp:DropDownList ID="drdCategory" runat="server">       
                            </asp:DropDownList>         
                               <asp:CascadingDropDown  ID="CascadingDropDown1" runat="server" Category="category"  TargetControlID="drdCategory"  PromptText="[Select Category]" LoadingText="Loading categories..." 
                                          ServicePath="ServiceTest.asmx"  
                                                    ServiceMethod="GetDropDownCategories">   </asp:CascadingDropDown>        
                                                    </td>    </tr>    <tr>        <td>           
     
                <b>Select Product :</b></td>        <td>           
                 <asp:DropDownList ID="drdProduct" runat="server" OnSelectedIndexChanged="drdProduct_SelectedIndexChanged" AutoPostBack="True">           
                  </asp:DropDownList>          
                    <asp:CascadingDropDown ID="CascadingDropDown2" runat="server"   Category="product"  TargetControlID="drdProduct"  ParentControlID="drdCategory"           
                     PromptText="[Select Product]"  LoadingText="Loading products..." ServicePath="ServiceTest.asmx" ServiceMethod="GetDropDownProducts">      
                           </asp:CascadingDropDown>        </td>    </tr>    <tr>     
     
                 <td colspan="2">      &nbsp;</td>    </tr>    <tr>   <td colspan="2"> 
                    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate>  
                     <asp:Label ID="Label1" runat="server" Font-Size="16px" ForeColor="Maroon" Style="padding: 5px;"></asp:Label>  </ContentTemplate> 
                      <Triggers>                   
                       <asp:AsyncPostBackTrigger ControlID="drdProduct" EventName="SelectedIndexChanged" />              
                         </Triggers>          
                           </asp:UpdatePanel>        </td>    </tr></table>
        </form>    
    </body>
    </html>
    Page test.aspx.cs :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
     
    namespace ProDoQ_Design
    {
        public partial class test : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
     
            }
     
            protected void drdProduct_SelectedIndexChanged(object sender, EventArgs e) 
            { 
                Label1.BackColor = System.Drawing.Color.FromName("#FFFF80");
                Label1.Text = string.Format("You selected <b>{0}</b> from <b>{1}</b> category.", drdProduct.SelectedItem.Text, drdCategory.SelectedItem.Text); 
            }
     
     
        }
    }
    Page ServiceTest.asmx.cs :


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    using System;
    using System.Web;
    using System.Collections;
    using System.Web.Services;
    using System.Web.Services.Protocols;
    using System.Collections.Generic;
    using AjaxControlToolkit;
    using System.Data;
    using System.Data.SqlClient;
    using System.Collections.Specialized;
    using System.Configuration;
     
    /// <summary>
    /// Description résumée de WebService
    /// </summary>
     
     
    public class ServiceTest : System.Web.Services.WebService
    {
     
     
     
        public ServiceTest()
        {
     
            //Supprimez les marques de commentaire dans la ligne suivante si vous utilisez des composants conçus 
            //InitializeComponent(); 
        }
     
     
     [WebMethod]
     public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownCategories(string knownCategoryValues, string category)
     {
         string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
         SqlConnection sqlConn = new SqlConnection(conString);   
         sqlConn.Open();   
         SqlCommand sqlSelect = new SqlCommand("SELECT * FROM Categories", sqlConn);  
         sqlSelect.CommandType = System.Data.CommandType.Text;   
         SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlSelect);  
         DataSet myDataset = new DataSet();  
         sqlAdapter.Fill(myDataset);   
         sqlConn.Close();   
         List<AjaxControlToolkit.CascadingDropDownNameValue> cascadingValues = new List<AjaxControlToolkit.CascadingDropDownNameValue>(); 
         foreach (DataRow dRow in myDataset.Tables[0].Rows)  
         {        string categoryID = dRow["categoryID"].ToString();    
                  string categoryName = dRow["categoryName"].ToString();       
                  cascadingValues.Add(new AjaxControlToolkit.CascadingDropDownNameValue(categoryName,categoryID)); 
         }    return cascadingValues.ToArray();
     }
     
      [WebMethod]
      public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownProducts(string knownCategoryValues, string category)
      {
          string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
          int categoryID; 
          StringDictionary categoryValues = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);  
          categoryID = Convert.ToInt32(categoryValues["category"]);  
          SqlConnection sqlConn = new SqlConnection(conString); 
          sqlConn.Open(); 
          SqlCommand sqlSelect = new SqlCommand("SELECT * FROM Products where categoryID = @categoryID", sqlConn); 
          sqlSelect.CommandType = System.Data.CommandType.Text;  
          sqlSelect.Parameters.Add("@categoryID", SqlDbType.Int).Value = categoryID; 
          SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlSelect);  
          DataSet myDataset = new DataSet();  
          sqlAdapter.Fill(myDataset);  
          sqlConn.Close();  
          List<AjaxControlToolkit.CascadingDropDownNameValue> cascadingValues = new List<AjaxControlToolkit.CascadingDropDownNameValue>();  
          foreach (DataRow dRow in myDataset.Tables[0].Rows) 
          {        string productID = dRow["productID"].ToString();     
                   string productName = dRow["productName"].ToString();     
                   cascadingValues.Add(new AjaxControlToolkit.CascadingDropDownNameValue(productName, productID)); 
          }    return cascadingValues.ToArray();
      }
     
     
     
    }

  13. #13
    Membre actif
    Profil pro
    Inscrit en
    Avril 2008
    Messages
    526
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2008
    Messages : 526
    Points : 224
    Points
    224
    Par défaut
    Autre possibilité : Est-ce qu'il faudrait mettre une référence dans le webconfig ?

  14. #14
    Membre du Club
    Inscrit en
    Juillet 2008
    Messages
    70
    Détails du profil
    Informations forums :
    Inscription : Juillet 2008
    Messages : 70
    Points : 54
    Points
    54
    Par défaut
    Ok, j'ai essayer ton code en changeant la partie SQL pour tester sur une base perso.

    Confirme moi une chose, ton webservice est il bien dans le asmx.cs ??

    Si oui, l'erreur est là, il devrait être dans le ServiceTest.asmx uniquement.
    Supprime le fichier asmx.cs et recopie tout ton code dans le .asmx.

    J'ai testé est ça marche bien ainsi, ton code n'a aucun défaut.

    Tiens moi au courant.

  15. #15
    Membre actif
    Profil pro
    Inscrit en
    Avril 2008
    Messages
    526
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2008
    Messages : 526
    Points : 224
    Points
    224
    Par défaut
    Bon j'ai fait ce que tu m'a dit mais toujours la même erreur. Je pense que c'est surrement une erreur dans mon accès aux données.

    Ce n'est pas grave, je le retesterais plus tard. J'ai bricolé deux listes déroulantes liées avec une mise à jour partielle, ça ira pour le moment.

    Merci pour tout ton aide.

Discussions similaires

  1. Réponses: 5
    Dernier message: 17/12/2007, 12h07
  2. Explication d'un article du tutoriel
    Par leSeb dans le forum VB.NET
    Réponses: 3
    Dernier message: 11/09/2007, 10h15
  3. Réseaux / Réplicats : tutoriels et explications ?
    Par seb92400 dans le forum Access
    Réponses: 12
    Dernier message: 15/03/2007, 13h55
  4. Besoin d'explication sur le passage d'arguments
    Par ChrOnOs83 dans le forum Flash
    Réponses: 3
    Dernier message: 16/11/2006, 11h23

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo