开发者

LINQ to perform action for correspning/related items, or databindg technique?

开发者 https://www.devze.com 2023-03-08 10:03 出处:网络
I have a ListBox that I populate from a database view, and then I want to add an attribute to each ListItem.Imagine if the user can select a City on the page and some javascript runs to filter down th

I have a ListBox that I populate from a database view, and then I want to add an attribute to each ListItem. Imagine if the user can select a City on the page and some javascript runs to filter down the listbox to only employees in that city. The javascript is no problem, but I need to add an attribute to each listitem that indicates what city the employee belongs to. Of course I could just have a couple loops where employeeID matches add the City. Is there was a better way using databinding or some sort of LINQ query to accomplish this?

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*/));

By adding the CityID attribute, my javascript/jquery will a way to filter the listbox as users select different cities. Note that I am not asking you to filter the list in advance, because that would require a postback everytime the user selects a City. I am just giving you this extra info because people often want to know more background than just the task at hand.


you can try something like that:

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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消