LINQ to XML绑定到asp.Net DropDownList

3

我正在尝试使用LINQ,以便将其绑定到ASP.NET下拉框。

到目前为止,这是我的LINQ表达式;我刚开始学习它,今天早上才开始接触。

 county.DataSource = (from taxUnit in TaxUnits.Descendants("CodeData")
    join taxType in TaxTypes.Descendants("CodeData")
      on
      taxUnit.Attribute("taxuntype").Value
      equals
      taxType.Attribute("codeid").Value
    where taxType.Attribute("taxuntypky").Value == "CO"
    select new
    {
      County = taxUnit.Attribute("desc"),
      CodeID = taxUnit.Attribute("codeid")
    });

  county.DataTextField = "desc";
  county.DataValueField = "codeid";

  county.DataBind();

最初我试图将它转换为datatable;有人告诉我,实际上可以直接使用LINQ绑定到DropDownList。

          <asp:Label AssociatedControlID="county" runat="server">County</asp:Label>
          <asp:DropDownList
            ID="county"
            runat="server" />

到目前为止,当我查看下拉框时,结果是...。根据我从LINQPad获取的信息,我期望

County CodeID 
Willow County 1 
CP2 TU 2

当前答案唯一的问题是我不知道它是如何工作的,因此我不明白如何将其转换为我想要的。

之前我能够使用一个指向该方法的ObjectDataSource,并为List创建一个模拟以进行数据绑定。


你知道你可以直接绑定LINQ结果而无需中间的DataSet吗? - abatishchev
不好意思,等我回到电脑前我再查一下。 - user1741874
LINQ生成的类应该具有您绑定的属性。并且要实现IList,即调用ToArray()ToList()。但是我在最后一句话可能是错误的。 - abatishchev
1个回答

1
如果实际问题是如何将LINQ到XML的结果绑定到DropDownList,那么以下是我旧ASP.NET项目中的代码。我将LINQ到Entities的结果绑定到GridView上。对于DropDownList应该也可以这样工作:
public IEnumerable<IDraft> Get(int accountId, DateTime startDate, DateTime endDate)
{
    using (var db = new ModelContainer())
    {
        var account = db.Accounts.SingleOrDefault(a => a.ID == accountId);
        return (from d in account.Drafts
                let date = d.Date.Date
                where startDate.Date <= date && date <= endDate.Date
                orderby d.Date ascending
                select d).ToArray();
    }
}

protected void gridView_OnDataBinding(object sender, EventArgs e)
{
    ((IDataBoundControl)sender).DataSource = IoC.Resolve<IOperationRepository>().GetShared(this.ObjectId.Value, ucChooseDate.StartDate, ucChooseDate.EndDate);
}

几个问题:IDraft是什么,您是否使用MVC,为什么您的方法比这种方法更好?https://dev59.com/qXRB5IYBdhLWcg3wro2B - user1741874
@xphill64x:IDraft是一个强类型实体。您可以使用强类型和弱类型(即匿名类)。 - abatishchev
不,这是“经典”的ASP.NET,也称为Web Forms。 - abatishchev
我假设这是你的代码后端;能否分享一下你在asp.net中的GridView?由于我对asp的理解有限,我肯定错过了某些东西。 - user1741874
正确的做法是使用LINQ to Entities/Entity Framework来绑定GridView从SQL Server中获取的数据。最初,这段代码使用了SqlConnection/SqlCommand,但后来被重写为使用ORM。 - abatishchev
让我们在聊天中继续这个讨论。 - user1741874

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接