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 Discussion :

[IHierarchicalEnumerable] Alimenter un menu/ treeview par entity


Sujet :

ASP.NET

  1. #1
    Membre confirmé
    Inscrit en
    Décembre 2004
    Messages
    157
    Détails du profil
    Informations personnelles :
    Âge : 43

    Informations forums :
    Inscription : Décembre 2004
    Messages : 157
    Par défaut [IHierarchicalEnumerable] Alimenter un menu/ treeview par entity
    Bonjour,

    Je suis à la recherche d'un moyen pour alimenter un menu avec mes donnée en base sans pour autant avoir besoin de créer mes MenuItem ou Nodes moi même.

    J'essaye d'alimenter mon menu avec le simple code qui suit :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    HMenu.DataSource = Sys_Menu.SelectAllForMenu("MainMenu", "FRA").ToHierarchicalEnumerable(item => item.Ident, item => item.ParentIdent);
            HMenu.DataBind();
    HMenu étant mon menu horizontale,
    Sys_Menu mon entité généré par entity framework.
    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
     
    // Identifiant de l'objet
            public string Ident { get; set; }
            // Identifiant de l'objet parent si non root
            public string ParentIdent { get; set; }
            // Nom à afficher
            public string Label { get; set; }
            // Nom du menu contenant ces objets
            public string MenuName { get; set; }
            // Numéro d'ordre de l'objet
            public int Ordre { get; set; }
            // Url de destination
            public string Url { get; set; }
            public string Image { get; set; }
            public string ImageMouseHover { get; set; }
    (Ça ne vient pas de mon code vu que c'est l'entity framework qui me l'a créé mais les propriétés sont identique tout en étant plus lisible.)

    Le ToHierarchicalEnumerable provient de la classe qui est expliqué dans le site que je vous mentionne plus haut.

    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
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    public static class LinqHierarchicalExtension
        {
            /// <summary>
            /// Convert an <see cref="System.Web.Collections.Generics.IEnumerable&lt;T&gt;"/> to a IHierarchicalEnumerable.
            /// </summary>
            /// <typeparam name="TElement">The type of the element.</typeparam>
            /// <typeparam name="TKey">The type of the key.</typeparam>
            /// <param name="elements">The original elements.</param>
            /// <param name="getCurrentID">The method to obtain the current node's ID.</param>
            /// <param name="getParentID">The method for obtain the current node's parent ID.</param>
            /// <param name="getPath">The method to obtain the current node's path.</param>
            public static IHierarchicalEnumerable ToHierarchicalEnumerable<TElement, TKey>(this IEnumerable<TElement> elements, Func<TElement, TKey> getCurrentID, Func<TElement, TKey> getParentID)
            {
                return ToHierarchicalEnumerable(elements, getCurrentID, getParentID, obj => String.Empty, obj => String.Empty);
            }
     
            /// <summary>
            /// Convert an <see cref="System.Web.Collections.Generics.IEnumerable&lt;T&gt;"/> to a IHierarchicalEnumerable.
            /// </summary>
            /// <typeparam name="TElement">The type of the element.</typeparam>
            /// <typeparam name="TKey">The type of the key.</typeparam>
            /// <param name="elements">The original elements.</param>
            /// <param name="getCurrentID">The method to obtain the current node's ID.</param>
            /// <param name="getParentID">The method for obtain the current node's parent ID.</param>
            /// <param name="getPath">The method to obtain the current node's path.</param>
            public static IHierarchicalEnumerable ToHierarchicalEnumerable<TElement, TKey>(this IEnumerable<TElement> elements, Func<TElement, TKey> getCurrentID, Func<TElement, TKey> getParentID, Func<TElement, String> getType)
            {
                return ToHierarchicalEnumerable(elements, getCurrentID, getParentID, getType, obj => String.Empty);
            }
     
            /// <summary>
            /// Convert an <see cref="System.Web.Collections.Generics.IEnumerable&lt;T&gt;"/> to a IHierarchicalEnumerable.
            /// </summary>
            /// <typeparam name="TElement">The type of the element.</typeparam>
            /// <typeparam name="TKey">The type of the key.</typeparam>
            /// <param name="elements">The original elements.</param>
            /// <param name="getCurrentID">The method to obtain the current node's ID.</param>
            /// <param name="getParentID">The method for obtain the current node's parent ID.</param>
            /// <param name="getPath">The method to obtain the current node's path.</param>
            /// <param name="getType">The method to obtain the current node's type.</param>
            public static IHierarchicalEnumerable ToHierarchicalEnumerable<TElement, TKey>(this IEnumerable<TElement> elements, Func<TElement, TKey> getCurrentID, Func<TElement, TKey> getParentID, Func<TElement, String> getType, Func<TElement, String> getPath)
            {
                var addedElements = new Dictionary<TKey, LinqNodeCollection<TElement, TKey>.LinqNode>();
                // l'appel de ToList() évite de se balader avec un QueryAble et faire beaucoup de requêtes SQL.
                return new LinqNodeCollection<TElement, TKey>(elements.ToList(), getCurrentID, getParentID, getType, getPath, addedElements);
            }
     
        }
     
        public sealed class LinqNodeCollection<TElement, TKey> : IHierarchicalEnumerable
        {
     
            private Boolean _isRootCollection = false;
     
            private IEnumerable<TElement> _currentElements;
            private IEnumerable<TElement> _originalElements;
            private Func<TElement, TKey> _getCurrentID;
            private Func<TElement, TKey> _getParentID;
            private Func<TElement, String> _getType;
            private Func<TElement, String> _getPath;
     
            Dictionary<TKey, LinqNode> _addedElements;
     
            /// <summary>
            /// Initializes a new instance of the <see cref="LinqNodeCollection&lt;TElement, TKey&gt;"/> class.
            /// </summary>
            /// <param name="originalElements">All elements of the initial collection.</param>
            /// <param name="getCurrentID">The method to obtain the current node's ID.</param>
            /// <param name="getParentID">The method for obtain the current node's parent ID.</param>
            /// <param name="getPath">The method to obtain the current node's path.</param>
            /// <param name="getType">The method to obtain the current node's type.</param>
            /// <param name="addedElements">The elements already added to the HierarchicalEnumerable.</param>
            public LinqNodeCollection(IEnumerable<TElement> originalElements, Func<TElement, TKey> getCurrentID, Func<TElement, TKey> getParentID, Func<TElement, String> getType, Func<TElement, String> getPath, Dictionary<TKey, LinqNode> addedElements)
                : this(originalElements, originalElements, getCurrentID, getParentID, getType, getPath, addedElements)
            {
                _isRootCollection = true;
            }
     
            /// <summary>
            /// Initializes a new instance of the <see cref="LinqNodeCollection&lt;TElement, TKey&gt;"/> class.
            /// </summary>
            /// <param name="originalElements">All elements of the initial collection.</param>
            /// <param name="currentElements">Child elements of this current elements (only direct children).</param>
            /// <param name="getCurrentID">The method to obtain the current node's ID.</param>
            /// <param name="getParentID">The method for obtain the current node's parent ID.</param>
            /// <param name="getPath">The method to obtain the current node's path.</param>
            /// <param name="getType">The method to obtain the current node's type.</param>
            /// <param name="addedElements">The elements already added to the HierarchicalEnumerable.</param>
            private LinqNodeCollection(IEnumerable<TElement> originalElements, IEnumerable<TElement> currentElements, Func<TElement, TKey> getCurrentID, Func<TElement, TKey> getParentID, Func<TElement, String> getType, Func<TElement, String> getPath, Dictionary<TKey, LinqNode> addedElements)
            {
                _currentElements = currentElements;
                _originalElements = originalElements;
                _getCurrentID = getCurrentID;
                _getParentID = getParentID;
                _getPath = getPath;
                _getType = getType;
                _addedElements = addedElements;
            }
     
            /// <summary>
            /// Gets the hierarchy data.
            /// </summary>
            /// <param name="enumeratedItem">The enumerated item.</param>
            /// <returns></returns>
            public IHierarchyData GetHierarchyData(object enumeratedItem)
            {
                var addedElement = new LinqNode(_originalElements, (TElement)enumeratedItem, _getCurrentID, _getParentID, _getPath, _getType, _addedElements);
                _addedElements.Add(_getCurrentID((TElement)enumeratedItem), addedElement);
                return addedElement;
            }
     
            /// <summary>
            /// Gets the enumerator.
            /// </summary>
            /// <returns></returns>
            public IEnumerator GetEnumerator()
            {
                IEnumerable<TElement> elements = null;
                if (_isRootCollection)
                {
                    elements = from e in _currentElements
                               where _getParentID(e) == null
                               select e;
                }
                else
                {
                    elements = _currentElements;
     
                }
     
                foreach (TElement element in elements)
                {
                    if (!_addedElements.ContainsKey(_getCurrentID(element)))
                    {
                        yield return element;
                    }
                }
     
            }
     
            public sealed class LinqNode : IHierarchyData
            {
                // contient la liste de tous les éléments enfants de ce noeud
                private IEnumerable<TElement> _children;
     
                // contient tous les éléments de la collection 
                private IEnumerable<TElement> _allElements;
                private TElement _element;
                private Func<TElement, TKey> _getCurrentID;
                private Func<TElement, TKey> _getParentID;
                private Func<TElement, String> _getPath;
                private Func<TElement, String> _getType;
     
                // contient tous les noeuds déjà traité 
                Dictionary<TKey, LinqNode> _addedElements;
     
                /// <summary>
                /// Initializes a new instance of the <see cref="LinqNodeCollection&lt;TElement, TKey&gt;.LinqNode"/> class.
                /// </summary>
                /// <param name="allElements">All elements of the initial collection.</param>
                /// <param name="element">The current element of this node.</param>
                /// <param name="getCurrentID">The method to obtain the current node's ID.</param>
                /// <param name="getParentID">The method for obtain the current node's parent ID.</param>
                /// <param name="getPath">The method to obtain the current node's path.</param>
                /// <param name="getType">The method to obtain the current node's type.</param>
                /// <param name="addedElements">The elements already added to the HierarchicalEnumerable.</param>
                internal LinqNode(IEnumerable<TElement> allElements, TElement element,
                    Func<TElement, TKey> getCurrentID, Func<TElement, TKey> getParentID,
                    Func<TElement, String> getPath, Func<TElement, String> getType,
                    Dictionary<TKey, LinqNode> addedElements)
                {
                    _allElements = allElements;
                    _element = element;
                    _getCurrentID = getCurrentID;
                    _getParentID = getParentID;
                    _getPath = getPath;
                    _getType = getType;
     
                    _addedElements = addedElements;
                }
     
     
                /// <summary>
                /// Gets an <see cref="T:System.Web.UI.IHierarchicalEnumerable"/> object that represents the children of current hierarchical node.
                /// </summary>
                /// <returns></returns>
                public IHierarchicalEnumerable GetChildren()
                {
                    ensureGetChildren();
                    return new LinqNodeCollection<TElement, TKey>(_allElements, _children, _getCurrentID, _getParentID, _getType, _getPath, _addedElements);
                }
     
                /// <summary>
                /// Gets an <see cref="T:System.Web.UI.IHierarchyData"/> object that represents the parent node of the current hierarchical node.
                /// </summary>
                /// <returns>
                /// An <see cref="T:System.Web.UI.IHierarchyData"/> object that represents the parent node of the current hierarchical node.
                /// </returns>
                public IHierarchyData GetParent()
                {
                    throw new NotImplementedException();
                }
     
                /// <summary>
                /// Indicates whether the hierarchical data node that the <see cref="T:System.Web.UI.IHierarchyData"/> object represents has any child nodes.
                /// </summary>
                /// <value></value>
                /// <returns>true if the current node has child nodes; otherwise, false.</returns>
                public bool HasChildren
                {
                    get
                    {
                        ensureGetChildren();
                        return _children.Count() > 0;
                    }
                }
     
                /// <summary>
                /// Gets the hierarchical data node that the <see cref="T:System.Web.UI.IHierarchyData"/> object represents.
                /// </summary>
                /// <value></value>
                /// <returns>An <see cref="T:System.Object"/> hierarchical data node object.</returns>
                public object Item
                {
                    get { return _element; }
                }
     
                /// <summary>
                /// Gets the hierarchical path of the node.
                /// </summary>
                /// <value></value>
                /// <returns>A <see cref="T:System.String"/> that identifies the hierarchical path relative to the current node.</returns>
                public string Path
                {
                    get { return _getPath(_element); }
                }
     
                /// <summary>
                /// Gets the name of the type of <see cref="T:System.Object"/> contained in the <see cref="P:System.Web.UI.IHierarchyData.Item"/> property.
                /// </summary>
                /// <value></value>
                /// <returns>The name of the type of object that the <see cref="T:System.Web.UI.IHierarchyData"/> object represents.</returns>
                public string Type
                {
                    get { return _getType(_element); }
                }
     
                private object _lock = new object();
                /// <summary>
                /// Get children of the current node.
                /// </summary>
                private void ensureGetChildren()
                {
                    lock (_lock)
                    {
                        if (_children == null)
                        {
                            _children = from e in _allElements
                                        where _getCurrentID(_element).Equals(_getParentID(e))
                                        select e;
                        }
     
                    }
                }
            }
        }

    Le hic est qu'ici si je ne change rien, le code crée des menu item avec le tostring de mon objet comme nom.

    Même si je surcharge ToString pour avoir un nom convenable, mon but est que
    MenuItem.NavigationUrl = Sys_Menu.Url
    MenuItem.Text = Sys_Menu.Libelle
    MenuItem.Value = Sys_Menu.Ident...

    J'imagine que ça doit être possible?

    Merci d'avance

  2. #2
    Membre Expert Avatar de Arthis
    Profil pro
    Inscrit en
    Octobre 2003
    Messages
    1 265
    Détails du profil
    Informations personnelles :
    Âge : 48
    Localisation : Italie

    Informations forums :
    Inscription : Octobre 2003
    Messages : 1 265
    Par défaut
    oui cela est possible as tu essayé quelque chose comme cela ou dans l'esprit en tout cas :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
     
    <asp:TreeView runat=server
    DataSource=<%# CatalogItems.ToHierarchicalEnumerable(cat => cat.ID, cat => cat.ParentId) %> >
         <DataBindings >
                 <asp:TreeNodeBinding TextField=Name ValueField=ID />
         </DataBindings>
    </asp:TreeView>
    moi je l utilise avec un treeview composant tiers mais je suis persuadé qu'avec l'original ca doit fonctionner aussi.

    Bon courage à toi

  3. #3
    Membre confirmé
    Inscrit en
    Décembre 2004
    Messages
    157
    Détails du profil
    Informations personnelles :
    Âge : 43

    Informations forums :
    Inscription : Décembre 2004
    Messages : 157
    Par défaut
    Merci beaucoup.

    J'ai tendance à ne pas vouloir toucher au code html vu que je travaille toujours en winform.

    Va falloir que je m'y fasse.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [D7] menu tronqué par une frame
    Par Magnus dans le forum Langage
    Réponses: 12
    Dernier message: 29/09/2009, 20h01
  2. Comment valider un items de Treeview par clic droit?
    Par Mickey.jet dans le forum Delphi
    Réponses: 8
    Dernier message: 10/05/2007, 17h23
  3. problème avec un menu généré par MySQL
    Par GhostDady dans le forum SQL Procédural
    Réponses: 5
    Dernier message: 30/03/2006, 10h45
  4. [VB.NET] Selectionner un noeud du treeview par le code
    Par Elbarto dans le forum Windows Forms
    Réponses: 7
    Dernier message: 23/02/2006, 10h49
  5. Menu déroulant par dessus tableau
    Par M1000 dans le forum Général JavaScript
    Réponses: 8
    Dernier message: 21/12/2005, 15h14

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