2010-04-14 53 views
1

我想從數據庫中創建一些動態html。我從db返回的數據是:在ASP.NET中通過分組呈現類似的數據

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

我希望單個應用程序的所有URL應該在ApplicationName的一個標題下呈現。像:

 
AppName1 

     URL1 

     URL2 

AppName2 

     URL1 

     URL2 

任何人都可以幫我在這個代碼?

+0

您可以指出您是否使用mvc或webforms;或者是其他東西?這樣就可以更容易地連接一個示例 – Thomas 2010-04-14 07:18:45

+0

這是簡單的webforms。 – Ashish 2010-04-14 07:21:09

回答

2

後面的代碼可能有這樣的事情,這樣你就可以訪問你的ASPX標記的項目:

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/")}, 
        }; 
} 

然後在你的aspx文件,簡單地拋出一些LINQ到混合進行分組操作:

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