简体   繁体   English

基于查询LINQ和ObjectDataSource的DDL DataTextField查询LINQ

[英]Query LINQ with DDL DataTextField based on query LINQ and ObjectDataSource

I have a problem with this dropdownlist based on an ObjectDataSource 我有一个基于ObjectDataSource的下拉列表有问题

<asp:DropDownList ID="DropDownList1" runat="server" 
                DataSourceID="UserODS" DataTextField="LastName"
                DataValueField="IDUser">
</asp:DropDownList>

<asp:ObjectDataSource ID="UserODS" runat="server" 
                SelectMethod="GetListFullNameUsers" TypeName="DAL.AccessoDB">
</asp:ObjectDataSource>

The method is: 方法是:

public List<String> GetListFullNameUsers()
{
   using (var context = new UChipDataContext())
   {
      return context.Users
                   .Select(c => new { c.LastName, c.FirstName })
                   .ToList()
                   .Select(c => String.Concat(c.LastName," ", c.FirstName))
                   .ToList(); 
   }
}

But I get this error: 但是我得到这个错误:

DataBinding: 'System.String' does not contain a property with the name 'LastName'. 数据绑定:“ System.String”不包含名称为“ LastName”的属性。

How can I solve? 我该如何解决?

Thanks in advance. 提前致谢。

Luigi 路易吉

OK... the problem here is the following: 好的...这里的问题如下:

Your LINQ query returns a list of plain strings and so your databinding fails because those strings don't have a property called LastName . 您的LINQ查询返回纯字符串列表,因此您的数据绑定失败,因为这些字符串没有名为LastName的属性。

One possible solution is to make the anonymous type into a class as shown here returning a strongly typed object with a property called LastName because you have DataTextField="LastName" and so your DropDownList does expect a property called LastName . 一种可能的解决方案是使匿名类型成为类,如此处所示返回具有属性LastName的强类型对象,因为您有DataTextField="LastName" ,因此DropDownList确实希望使用名为LastName的属性。

Hrm why do you have multiple select / tolists?? 嗯,为什么您有多个选择/列表?

Try this: 尝试这个:

    return context.Users
                  .Select(c => string.Format("{0} {1}", c.LastName, c.FirstName))
                  .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM