Home > Enterprise >  How to make autopostback Multiselect ListBox in ASP?
How to make autopostback Multiselect ListBox in ASP?

Time:12-23

I am trying to make a multi-select ListBox in ASP.NET using a ListBox control with Bootstrap Multiselect styling.

In regards to appearance, it works well. I can toggle it to drop down, I can select and deselect options and close it.

<asp:ListBox ID="NameListBox" runat="server" CssClass="multiselect" SelectionMode="Multiple" OnSelectedIndexChanged="NameListBox_SelectedIndexChanged">
    <asp:ListItem Text="Name 1" />
    <asp:ListItem Text="Name 2" />
    <asp:ListItem Text="Name 3" />
    <asp:ListItem Text="Name 4" />
    <asp:ListItem Text="Name 5" />
    <asp:ListItem Text="Name 6" />
</asp:ListBox>

What I have a problem with is making a postback and handling the newly selected items. I have an OnSelectedIndexChanged written where I loop through the selected items and insert them into the database, but I don't know when and how to run it. I know I could have a separate button to cause a postback and save the selected items, but I would like to cause an automatic postback when closing the ListBox.

The problem is, if I use AutoPostBack="true", then postback will happen with every option change, so the user has no way to select more options than save at once. I only want to cause a postback when the dropdown list is actually closed.

After many tries, I got to this:

$('.multiselect').multiselect({
            nonSelectedText: '',
            nSelectedText: 'selected',
            allSelectedText: 'Everyone',
            numberDisplayed: 2,
            buttonTextAlignment: 'left',
            buttonWidth: 240,
            onDropdownHidden: function (event) {
                __doPostBack($(event.target).parent().children('.multiselect').attr('id'), '');
            }
            });

This causes a postback after closing the list box's drop-down list, which is good. But sadly, the NameListBox_SelectedIndexChanged event handler doesn't get fired during the postback, so nothing happens.

Any tips?

CodePudding user response:

hope this can help you~

<asp:ListBox ID="DropDownList_ExportCountry" runat="server" SelectionMode="Multiple" OnSelectedIndexChanged="DropDownList_ExportCountry_SelectedIndexChanged"></asp:ListBox>

after html <form I put this

<script type="text/javascript">
$('[id*=DropDownList_ExportCountry]').multiselect({
        onDropdownHide: function (event) {
            __doPostBack();//__doPostBack($(event.target).parent().children('#DropDownList_ExportCountry').attr('id'), '')
        }
    });

and remember include js and Css like this in <head

<link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
<script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>
  • Related