如何在aspx页面访问linq查询的属性

本文关键字:linq 查询 属性 访问 aspx | 更新日期: 2023-09-27 18:06:24

我从三个对象列表中返回一个这样的列表*感谢@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();

这是我的listview:

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

如何在aspx页面访问linq查询的属性

您只需设置ListView.DataSource = joined,然后调用DataBind(),您可以通过Eval()Bind()在您的ListView模板中访问它们,请参阅MSDN文档中的ListView控件的其他示例

回答问题的第一部分,匿名类型可以像其他类型一样用作数据源。ASP。. NET将对源代码进行反射,并找到它需要的任何属性。

myListView.DataSource = joined;
myListView.DataBind();
然后,在ListView中访问这些属性,只需使用Bind和Eval。这里有一些关于数据绑定的文档,可以帮助您入门

这里有两个问题:

您还没有完全枚举集合-您可能应该调用.ToList().ToArray()之类的聚合器。

另外,您正在创建一个匿名对象作为结果。在该代码的特定作用域之外,没有任何东西知道该对象包含什么属性。如果您想在其他地方使用该对象,则应该切换到具有已知属性的预定义类。