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);
}
精彩评论