简体   繁体   中英

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

I have a ListBox on which I have applied a Chosen Jquery plugin. So on Page load I go to DB and bind the items. This works fine with all its autocomplete feature etc. Then I update these values to Database.

When I reaload this item , I want to take the previously saved value and make it the selected Item.

I can get ListItems for which I need to set the Selected Proprty to true . But when I try the code below nothing happens. The Box is empty and no item is selected. How I can so this. Is there a way to kick this off from C# code behind ?

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

my Control looks like

<%@ 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>

Essentially at a DataBound event I want to reset the selected items which are saved in DB. PS: I am using Chosen 1.3 , ASP.NET 4.0

Thanks in advance

Added this in the OnDataBound event

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

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM