在多选 asp 列表框(使用 jQuery 插件选定)中设置所选项

Set selected items in a Multiselect asp Listbox (which uses jQuery plugin-Chosen )

本文关键字:选项 插件 设置 使用 asp 列表 jQuery      更新时间:2023-09-26

我有一个ListBox,我在其上应用了一个Selected Jquery插件。因此,在页面加载时,我转到数据库并绑定项目。这适用于其所有自动完成功能等。然后我将这些值更新到数据库。

当我重新加载此项目时,我想获取先前保存的值并使其成为选定的项目。

我可以获取需要将所选属性设置为 true 的列表项。但是当我尝试下面的代码时,没有任何反应。"框"为空,未选择任何项目。我怎么能这样。有没有办法从后面的 C# 代码开始?

    foreach (ListItem li in mySelectedListItemCollection)
    {
        if (li.Selected)
        {
            ddlMultiSelect.Items.FindByValue(li.Value).Selected = true 
        }
    }

我的控件看起来像

<%@ Control Language="C#" CodeBehind="Edit.ascx.cs" blah blah %>   
 <asp:ListBox ID="ddlMultiSelect" SelectionMode="Multiple" data-placeholder="Choose…" class="chosen-select"  multiple Style="width: 350px;" runat="server">
    </asp:ListBox>

    <form>
        <script type="text/javascript">
    var config = {
    '.chosen-select': {},
    '.chosen-select-deselect': { allow_single_deselect: true },
    '.chosen-select-no-single': { disable_search_threshold: 10 },
    '.chosen-select-no-results': { no_results_text: 'Oops, nothing found!' },
    '.chosen-select-width': { width: "95%" }
    }
    for (var selector in config) {
        $(selector).chosen(config[selector]);
    }
    </script>
    </form>
    <header>
        <script type="text/javascript">
        $(document).ready(function () {
            $("#<%=ddlMultiSelect.ClientID %>").change(function () {
                var arr = $(this).val();
                if (typeof arr === 'object' && arr instanceof Array) {
                    document.getElementById('<%=lbltest.ClientID%>').value = arr.toString();
                }
                else { document.getElementById('<%=lbltest.ClientID%>').value = ""; }
        console.log(arr)})
    });
    </script>
    </header>

本质上,在 DataBound 事件中,我想重置保存在数据库中的选定项目。PS:我正在使用 选择1.3 ,ASP.NET 4.0

提前致谢

在 OnDataBound 事件中添加了这个

    foreach (object childEntity in childTable.GetQuery(ObjectContext))
    {
        ListItem listItem = new ListItem(
            childTable.GetDisplayString(childEntity),
            childTable.GetPrimaryKeyString(childEntity));
        if (Mode == DataBoundControlMode.Edit)
        {
            listItem.Selected = ListContainsEntity(childTable, entityCollection, childEntity);
        }
        ddlMultiSelect.Items.Add(listItem);
        }