LINQ执行针对对应/相关项目的操作,还是databindg技术?

问题描述

| 我有一个从数据库视图填充的ListBox,然后想向每个ListItem添加一个属性。想象一下,如果用户可以在页面上选择城市,然后运行一些JavaScript来过滤列表框,使其仅过滤该城市中的员工。 javascript没问题,但是我需要向每个列表项添加一个属性,以指示该员工所属的城市。当然,我可以有几个循环,其中employeeID匹配添加城市。有没有更好的方法使用数据绑定或某种LINQ查询来完成此任务?
employeesListBox.DataSource = (from p in dwEntitiesContext.Employees
                                      orderby p.name
                                      select p).ToList();

      employeesListBox.DataTextField = \"Full Name\";
      employeesListBox.DataValueField = \"EmployeeID\";
      employeesListBox.DataBind();

      //this gives you the idea of what I want to do,//but obviously I can\'t access p.City here
      //Was wondering if there was some technique of doing a join,//or some way to databind the attribute
      employeesListBox.Items.Cast<ListItem>().Select(eachItem => 
      eachItem.Attributes.Add(\"CityID\",p.City 
      /*set City attribute of the employee this listitem represents*/));
通过添加CityID属性,我的javascript / jquery将可以在用户选择其他城市时过滤列表框。请注意,我并不是要您预先过滤列表,因为每次用户选择城市时,这都需要回发。我只是向您提供这些额外的信息,因为人们经常想知道更多的背景知识,而不仅仅是手头的任务。     

解决方法

您可以尝试类似的方法:
foreach(var employee in dwEntitiesContext.Employees.OrderBy(e => e.name))
{
    var listItem = new ListItem
        {
            Text = employee.FullName,Value = employee.EmployeeID
        };

    listItem.Attributes.Add(\"CityID\",employee.City);

    employeesListBox.Items.Add(listItem);
}
    

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...