簡體   English   中英

如何在aspx頁面中訪問linq查詢的屬性?

[英]How to access properties of a linq query in aspx page?

我要從三個對象列表中返回這樣的列表*感謝@sehe

        `var joined = from p in personList
         join par in relations
             on p.Id equals par.PersonId
         join a in addressList
             on a.Id equals par.AddressId
         select new { Person = p, Address = a };`

如何設置join作為listview的數據源並訪問aspx頁面中的屬性?

好的,這里有一些代碼可能會有所幫助,因為我得到了兩個不同的答案。

//背后的代碼

    protected void Page_Init(object sender, EventArgs e)
{
    List<Customer> customers = Customer.GetAllCustomers();
    List<Address> addresses = Address.GetAllAddresses();
    List<AddressRelation> addressRelations = AddressRelation.GetAllAddressRelations();
    var results = from c in customers
                  join rel in addressRelations
                  on c.CustomerID equals rel.CustomerID
                  join a in addresses
                  on rel.CustomerAddressID equals a.CustomerAddressID

                  select new
                  {
                      FirstName = c.FirstName,
                      LastName = c.LastName,
                      PhoneNumber = c.PhoneNumber,
                      AddressLine = a.AddressLine1,
                      CustomerCity = a.City,
                      CustomerZip = a.ZipCode
                  };

    ListView1.DataSource = results;
    ListView1.DataBind();

這是我的列表視圖:

            `<asp:ListView ID="ListView1" runat="server" >`
            `<LayoutTemplate>`
             <ul style="float:left; width:250px">
             <asp:PlaceHolder ID="itemPlaceHolder" runat="server"></asp:PlaceHolder>
             </ul>
             </LayoutTemplate>
             <ItemTemplate>
             <li><%# Eval("FirstName") %></li>
             <li><%# Eval("AddressLine") %></li>
             </ItemTemplate>
             <ItemSeparatorTemplate><hr /></ItemSeparatorTemplate>
             </asp:ListView>

您只需設置ListView.DataSource = joined ,然后調用DataBind()您可以通過Eval()Bind()在ListView模板中訪問它們。有關其他示例,請參閱ListView控件MSDN文檔

要回答問題的第一部分,匿名類型可以像任何其他類型一樣用作數據源。 ASP.NET將反映源代碼並找到它需要的任何屬性。

myListView.DataSource = joined;
myListView.DataBind();

然后,要在ListView中訪問這些屬性,只需使用Bind和Eval。 這里有一些關於數據綁定文檔,可以幫助您入門

這里有兩個問題:

您尚未完全枚舉該集合 - 您應該調用聚合器,如.ToList().ToArray()

此外,您正在創建一個匿名對象作為結果。 在該代碼的特定范圍之外,什么都不知道該對象包含哪些屬性。 如果要在其他位置使用該對象,則應切換到具有已知屬性的預定義類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM