views:

24

answers:

1

I am trying to create some dynamic html out of some data from db. My data returned from db is:

ApplicationName       URL
------------------------------
AppName1              URL1
AppName2              URL1
AppName2              URL2
AppName1              URL2

I want that all URL's for a single application should be rendered under one heading of ApplicationName. Like:

AppName1

      URL1

      URL2

AppName2

      URL1

      URL2

Can anyone help me in the code for this?

+1  A: 

Your code behind probably has something like this, so you can access the items in your aspx markup:

public Item[] DataItems { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    // get your list
    DataItems = new[]
                    {
                        new Item{ ApplicationName = "Test", Url = new Uri("http://test.com/Home")},
                        new Item{ ApplicationName = "Test", Url = new Uri("http://test.com")},
                        new Item{ ApplicationName = "Test 2", Url = new Uri("http://test2.com/Home")},
                        new Item{ ApplicationName = "Test 2", Url = new Uri("http://test2.com/")},
                    };
}

Then in your aspx file, simply throw in some linq into the mix to perform the grouping operation:

 <ul>
<% foreach (var aggregateItem in (from item in DataItems
                                  group item by item.ApplicationName
                                  into groupedItem
                                  select new { Name = groupedItem.Key, Items = groupedItem })) %>
<% { %>

    <li><strong><%= aggregateItem.Name%></strong>
        <ul>
            <% foreach (var subItem in aggregateItem.Items) %>
            <% { %>
                <p>
                    <a href="<%= subItem.Url %>"><%= subItem.Url %></a>
                </p>
            <% } %>
        </ul>
    </li>
<% } %>
</ul>
Thomas