2011-05-26 11 views
0

我有一個ListBox,我從數據庫視圖填充,然後我想向每個ListItem添加一個屬性。試想一下,如果用戶可以在頁面上選擇一個城市,並且某些JavaScript運行時將列表框過濾爲僅限該城市的員工。 javascript沒有問題,但我需要爲每個listitem添加一個屬性,以指示該員工屬於哪個城市。當然,我可以在僱員ID匹配的地方添加城市。 是否有更好的方法使用數據綁定或某種類型的LINQ查詢來完成此操作?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將一種方式來爲用戶選擇不同的城市篩選列表框。請注意,我不會要求您提前過濾列表,因爲每次用戶選擇城市時都需要回發。我只是給你這個額外的信息,因爲人們往往想知道更多的背景,而不僅僅是手頭的任務。

回答

1

你可以嘗試這樣的事情:

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

嗯,這摒棄了綁定,這是我一直試圖使用數據綁定,因爲這是我已經習慣了。我知道Win表單應用程序具有很多好處。儘管我從來沒有發現它在ASP.NET應用程序中非常有用,因爲你的代碼不再比我的代碼更好,它似乎完成了數據綁定所做的同樣的事情,並且讓我懷疑爲什麼我會爲數據綁定而煩惱。 – AaronLS 2011-05-26 16:49:58