<script type="text/javascript">
function pageLoad() {
$("#<%= DepartmentsListBox.ClientID %>").multiselect({
create: function () {
$(this).data("initValues", $.map($("option:selected", this), function (option) { return option.value; }).join(","));
},
close: function () {
var selectedValues = $.map($("option:selected", this), function (option) { return option.value; }).join(",");
if (selectedValues !== $(this).data("initValues")) {
__doPostBack("<%= DepartmentsListBox.UniqueID %>", "");
}
}
});
$("#<%= EmployeesListBox.ClientID %>").multiselect();
}
</script>
<asp:UpdatePanel runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:ListBox runat="server" ID="DepartmentsListBox" DataValueField="DepartmentId"
SelectionMode="Multiple" DataTextField="Name" Width="300px"></asp:ListBox>
<br />
<asp:ListBox runat="server" ID="EmployeesListBox" Width="300px" SelectionMode="Multiple" AppendDataBoundItems="true"
DataValueField="EmployeeId" DataTextField="Name"></asp:ListBox>
<br />
<asp:Button runat="server" ID="SubmitButton" Text="Submit" />
</ContentTemplate>
</asp:UpdatePanel>
服务器代码
private static Random rnd = new Random();
private string[] selectedDepartments;
private string[] SelectedDepartments
{
get
{
return selectedDepartments ?? (selectedDepartments = DepartmentsListBox.Items.OfType<ListItem>().Where(item => item.Selected).Select(item => item.Value).ToArray());
}
}
protected void Page_Init(object sender, EventArgs e)
{
EmployeesListBox.PreRender += new EventHandler(EmployeesListBox_PreRender);
DepartmentsListBox.SelectedIndexChanged += new EventHandler(DepartmentsListBox_SelectedIndexChanged);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDepartments();
}
}
void EmployeesListBox_PreRender(object sender, EventArgs e)
{
if (EmployeesListBox.Items.Count > 0)
{
EmployeesListBox.Attributes.Remove("disabled");
}
else
{
EmployeesListBox.Attributes["disabled"] = "disabled";
}
}
private void BindDepartments()
{
var departments = Enumerable.Range(1, 10)
.Select(id => new { DepartmentId = id, Name = "Department " + id.ToString() });
DepartmentsListBox.DataSource = departments;
DepartmentsListBox.DataBind();
}
void DepartmentsListBox_SelectedIndexChanged(object sender, EventArgs e)
{
var employees = Enumerable.Range(1, 10)
.Select(id => new { EmployeeId = id, DepartmentId = rnd.Next(1, 10), Name = "Employee #" + id.ToString() })
.Where(emp => SelectedDepartments.Contains(emp.DepartmentId.ToString())).ToList();
for (int itemIndex = EmployeesListBox.Items.Count - 1; itemIndex >= 0; itemIndex--)
{
var employee = employees.FirstOrDefault(emp => emp.EmployeeId.ToString() == EmployeesListBox.Items[itemIndex].Value);
if (employee == null)
{
EmployeesListBox.Items.RemoveAt(itemIndex);
}
else
{
employees.Remove(employee);
}
}
EmployeesListBox.DataSource = employees;
EmployeesListBox.DataBind();
}