.NET Blog

Tony Cavaliere

 
My Favourite Albums
  And the Grappa wins.
E-mail me Send mail

Disclaimer

Hey unlike other bloggers I stand by what I say but just in case. The opinions expressed herein are my own except on Tuesday when the second card is not turned up otherwise it ain't worth squat.

© Copyright 2012

LINQ to XML, Object Graphs and the ListView control

I have a subscription to msdn magazine and am a regular reader. I especially try to read all the articles on any ASP.NET related topics. Dino Exposito is a regular contributor to this magazine and has written many great articles on ASP.NET. In the April 2008 he wrote an excellent article on the new ASP.NET ListView control, specially, he discusses in detail how to bind a ListView control to hierarchical data.

This is by no means the first article that I have read on the topic of ListView controls. In all the articles or blog postings that I have read, I have yet to see how to use LINQ to create custom objects with complex object graphs. Instead anonymous types are used. In this post I will demonstrate how to create a custom object graph from a LINQ to XML query. Furthermore, I will bind this object to a nested ListView control. I will use the same example as presented by Dino in the August edition of msdn magazine.

We will be creating a hierarchical menu that is rendered using LINQ to XML, ListView control and an XML file. Listing 1 shows the menu.xml file.

Listing 1: menu.xml

<?xml version="1.0" encoding="utf-8" ?>

<menu>

  <item>

    <title>Menu Title 1</title>

    <link url="url1-1" text="text1-1"></link>

    <link url="url1-2" text="text1-2"></link>

    <link url="url1-3" text="text1-3"></link>

    <link url="url1-4" text="text1-4"></link>

  </item>

  <item>

    <title>Menu Title 2</title>

    <link url="url2-1" text="text2-1"></link>

    <link url="url2-2" text="text2-2"></link>

    <link url="url2-3" text="text2-3"></link>

  </item>

  <item>

    <title>Menu Title 3</title>

    <link url="url3-1" text="text3-1"></link>

    <link url="url3-2" text="text3-2"></link>

  </item>

</menu>

The schema of this XML file is straight forward. Each <item> node contains a menu title and then has 1 or more links. Each link has the URL to navigate too and the title that is to be used as textual display for the link.

Ultimately we would like to bind this data to a nested ListView control. The markup for this nested ListView control is shown in Listing 2. The title is render in the outer ListView control, whereas, the links are render in the inner ListView control. The code bind will be responsible for binding the outer ListView. The inner is bound declaratively. Please note that DataSource for the inner ListView control must be named links.

List 2: Nested ListView Control

    <asp:ListView ID="ListViewMenu" runat="server" ItemPlaceholderID="PlaceHolder1">

 

      <LayoutTemplate>

          <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

      </LayoutTemplate>

      <ItemTemplate>

 

        <h1><%# Eval("title")%></h1>

 

        <asp:ListView ID="ListViewSubMenu" runat="server"

          DataSource='<%# Eval("links") %>' ItemPlaceholderID="PlaceHolder2">

 

          <LayoutTemplate>

            <ul><asp:PlaceHolder ID="PlaceHolder2" runat="server"></asp:PlaceHolder></ul>

          </LayoutTemplate>

 

          <ItemTemplate>

            <li><a href='<%# Eval("url") %>'><%#Eval("text")%></a></li>

          </ItemTemplate>

 

        </asp:ListView>

      </ItemTemplate>

    </asp:ListView>

Before we use custom objects, let's review how we can use LINQ to XML and anonymous types as a data source to a ListView control. Listing 3 shows the code behind that accomplishes this.

List 3: Binding ListView Control with an Anonymous Type

        Dim doc As XDocument = XDocument.Load(Server.MapPath("App_Data/Menu.xml"))

        Dim menu = From mi In doc.<menu>.<item> _

                   Select _

                        title = mi.<title>.Value, _

                        links = From link In mi.<link> _

                                Select _

                                    url = link.@url, _

                                    [text] = link.@text

 

        ListViewMenu.DataSource = menu

        ListViewMenu.DataBind()

In this code snippet we are using the LINQ to XML features of VB.NET to query the XML file. The doc.<menu>.<item> retrieves all the <item> children for the document. The content of the <item> node is loaded into an anonymous type having two properties; title and links. The property links is a collection that is populated by the sub query. In the end, the anonymous type, menu is of type IEnumerable(Of <anonymous type>). The menu object is then used as data source to the outer ListView control.

Anonymous type are great, however, there are cases when you may need to pass the data between methods, tiers or even across process boundaries. In this scenario you should us a custom type. To do this you must first create the classes. In our case two classes are required. Listing 4 shows the two classes.

List 4: Custom Types 

<DebuggerStepThrough()> _

Public Class Menu

    <DebuggerBrowsable(DebuggerBrowsableState.Never)> _

    Private _title As String

    Public Property title() As String

        Get

            Return _title

        End Get

        Set(ByVal value As String)

            _title = value

        End Set

    End Property

    <DebuggerBrowsable(DebuggerBrowsableState.Never)> _

    Private _links As IEnumerable(Of Link)

    Public Property links() As IEnumerable(Of Link)

        Get

            Return _links

        End Get

        Set(ByVal value As IEnumerable(Of Link))

            _links = value

        End Set

    End Property

End Class

 

<DebuggerStepThrough()> _

Public Class Link

    <DebuggerBrowsable(DebuggerBrowsableState.Never)> _

    Private _url As String

    Public Property url() As String

        Get

            Return _url

        End Get

        Set(ByVal value As String)

            _url = value

        End Set

    End Property

    <DebuggerBrowsable(DebuggerBrowsableState.Never)> _

    Private _text As String

    Public Property text() As String

        Get

            Return _text

        End Get

        Set(ByVal value As String)

            _text = value

        End Set

    End Property

End Class

The two classes are named, Menu and Link. Menu contains two properties; title and links. links is of type IEnumerable(Of Link) which is important as LINQ queries of this type return the generic type IEnumerable(Of T). I have tried other generic types that derive from IEnumerable(Of T) such as List(Of T) but they generate Unable to cast object of type... exception. Perhaps there is a way to explicitly cast the object but that would require further investigation. Perhaps a future blog post?

Listing 5 shows LINQ to XML code to make use of the custom type.

List 5: Binding ListView Control with a Custom Type

        Dim doc As XDocument = XDocument.Load(Server.MapPath("App_Data/Menu.xml"))

        Dim menu = From mi In doc.<menu>.<item> _

                   Select New Menu With { _

                        .title = mi.<title>.Value, _

                        .links = From l In mi.<link> _

                                Select New Link With { _

                                    .url = l.@url, _

                                    .[text] = l.@text _

                            } _

                    }

        ListViewMenu.DataSource = menu

        ListViewMenu.DataBind()

The menu object is now of type IEnumerable(Of Menu), which can be easily passed as a parameter to a method or serialized across the wire.

Guess the movie

You loved my father, I know. But so did I. That makes us brothers, doesn't it? Smile for me now, brother.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: ASP.NET | VB.NET | LINQ | XML
Posted by CynotWhyNot on Wednesday, April 16, 2008 4:10 PM
Permalink | Comments (44) | Post RSSRSS comment feed

Related posts

Comments

buenos aires apartment rental us

Monday, November 16, 2009 3:11 AM

buenos aires apartment rental

Hi nice to read this I realy like to


Regards
Golden


Certified Financial Planner Raleigh us

Saturday, November 21, 2009 5:50 AM

Certified Financial Planner Raleigh

This is the best post on this topic i have ever read.


Regards

Pitter

discount designer bags US

Thursday, May 27, 2010 2:36 PM

discount designer bags

Amazing article. Bookmarked it already. Best regards, Ken.

wallets US

Tuesday, June 01, 2010 3:02 PM

wallets

You did the a great work writing and revealing the hidden beneficial features of BlogEngine.Net, that I found it was popularly used by bloggers nowadays. I think BE has emerged to be one of the best blogging platform right now. I wish you good luck with your blogging experiences.

discount prada bags US

Friday, June 25, 2010 9:59 AM

discount prada bags

I find your blog in google. And I will be back next time, thanks.

foam mattresses us

Tuesday, October 12, 2010 9:02 PM

foam mattresses

wtslhnxwgxymxdxrol, http://www.lastingimpressionsfoam.com , mSzzzRnFxnxMgEnrSnCj.

no xplode us

Saturday, October 16, 2010 5:30 PM

no xplode

nvbwnrnohzfbpraxmo, http://www.affordablesupplementstore.co.uk , bYeoaWLDsjuloRaUyyVh.

Cross cutting shredder us

Sunday, November 07, 2010 9:46 AM

Cross cutting shredder

This site is cool. i visit here evaryday.

Patriot 32gb razzo usb drive with ready boost ready vista certified psf32grusb

This site is great. i visit here evaryday.

Finishing and blending face antibacterial makeup brush 955 studio line

Thanks for posting this. i really had good time reading this.

How to apply makeup us

Sunday, November 07, 2010 6:20 PM

How to apply makeup

This site is cool. i visit here evaryday.

Eliza Dushku 35 HD Wallpaper us

Sunday, November 07, 2010 9:15 PM

Eliza Dushku 35 HD Wallpaper

I liked this post

Facebook statuses us

Monday, November 08, 2010 12:10 AM

Facebook statuses

I loved this article

Emo us

Monday, November 08, 2010 2:56 AM

Emo

Where can i find your rss? I cant find it

Compact refrigerator us

Monday, November 08, 2010 5:46 AM

Compact refrigerator

Thanks for posting this. i really had good time reading this.

Cross cutting shredder us

Monday, November 08, 2010 8:33 AM

Cross cutting shredder

This site is great. i visit here evaryday.

Just cavalli her by roberto cavalli 2 0 oz 60 ml women eau de toilette brand new in sealed box

Thanks for posting this. i really had good time reading this.

Make up tips to rejuvenate yourself us

Tuesday, November 16, 2010 3:35 PM

Make up tips to rejuvenate yourself

Great site design!!!! Whattemplate did you use?

2011 Porsche 911 Turbo S 2 HD Wallpaper us

Tuesday, November 16, 2010 9:12 PM

2011 Porsche 911 Turbo S 2 HD Wallpaper

Where can i find your rss? I cant find it

Facebook statuses us

Wednesday, November 17, 2010 1:09 AM

Facebook statuses

This site is great. i visit here evaryday.

Emo us

Wednesday, November 17, 2010 5:09 AM

Emo

Where is your rss? I cant find it

Compact refrigerator us

Wednesday, November 17, 2010 9:03 AM

Compact refrigerator

Hey check out my blog too. I hope i have some interesting stuff too

Cross cutting shredder us

Wednesday, November 17, 2010 12:52 PM

Cross cutting shredder

Where is your rss? I cant find it

White night us

Wednesday, November 17, 2010 4:59 PM

White night

I loved this post

The night angel trilogy us

Wednesday, November 17, 2010 9:18 PM

The night angel trilogy

Its a pity you dont have a donate button, i would donate some =)

What is the appropriate hairstyle for male airline cabin crew

Its a pity you dont have a donate button, i would donate some =)

Megan Fox (16) HD Wallpaper us

Thursday, November 25, 2010 5:03 PM

Megan Fox (16) HD Wallpaper

This site is cool. i visit here evaryday.

A Dreamy World HD Wallpaper us

Monday, December 06, 2010 3:21 AM

A Dreamy World HD Wallpaper

Hey check out my blog too. I hope i have some cool stuff too

Facebook statuses us

Tuesday, December 07, 2010 2:23 AM

Facebook statuses

This site is great. i visit here evaryday.

Emo us

Tuesday, December 07, 2010 8:09 AM

Emo

This site is great. i visit here evaryday.

Compact refrigerator us

Wednesday, December 08, 2010 1:39 AM

Compact refrigerator

I liked this post

Cross cutting shredder us

Wednesday, December 08, 2010 7:50 AM

Cross cutting shredder

Thanks for posting this. i really had good time reading this.

Castle link usb programmer adapter us

Wednesday, December 08, 2010 2:24 PM

Castle link usb programmer adapter

Where is your rss? I cant find it

Champions of ruin us

Thursday, December 09, 2010 7:53 AM

Champions of ruin

Great site design!!!! Whattemplate did you use?

Secrets of xendrik us

Thursday, December 09, 2010 2:25 PM

Secrets of xendrik

Where can i find your rss? I cant find it

Fox girls tribute us

Friday, December 10, 2010 3:09 AM

Fox girls tribute

Hey check out my blog too. I hope i have some interesting stuff too

What type of cell phone do you suggest for a 13 year old girl

Thanks for posting this. i really enjoyed reading this.

Facebook statuses us

Monday, December 13, 2010 1:00 AM

Facebook statuses

Hey check out my blog too. I hope i have some cool stuff too

Compact refrigerator us

Tuesday, December 14, 2010 4:08 AM

Compact refrigerator

Hey check out my blog too. I hope i have some cool stuff too

Cross cutting shredder us

Tuesday, December 14, 2010 1:07 PM

Cross cutting shredder

Great site design!!!! Whattemplate did you use?

Free xbox live codesworking 2010 update 12 22 2010 us

Saturday, December 25, 2010 11:49 AM

Free xbox live codesworking 2010 update 12 22 2010

This site is cool. i visit here evaryday.

Attitude facebook statuses us

Sunday, December 26, 2010 9:21 AM

Attitude facebook statuses

Hey check out my blog too. I hope i have some interesting stuff too