Search code examples
c#jquerymulti-selectasp.net-mvc-5bootstrap-selectpicker

Bootstrap Selectpicker multiselect doesn't keep selection after submit


I am using the bootstrap selectpicker for a multiselect dropdown menu to filter items of a table in a mvc5 web app. Everything works fine so far, but i am having trouble to keep the selected filters selected after submitting. So i can read the selected filters in the controller, but after that, there is only the first previously selected filter still shown as selected after the submit. I want all chosen filters to be still selected. How can I reach this?

Here ist my Code, the ViewModel contains:

        public MultiSelectList AvailableUser_ID { get; set; }

        private List<string> _selectedUserId = new List<string>();
        public List<string> SelectedUserId
        {
            get { return _selectedUserId; }
            set { _selectedUserId = value; }
        }

The Controller (Post):

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "SelectedUserId,SelectedUserInteractionTypesId")] IndexUserInteractionViewModel indexUserInteractionViewModel)
    {
         indexUserInteractionViewModel.UserInteractionViewModels = new List<UserInteractionViewModels>();
         indexUserInteractionViewModel.AvailableUser_ID = new MultiSelectList(db.AspNetUsers.ToList(), "Id", "Email", indexUserInteractionViewModel.SelectedUserId);

    // Filter Function: selectedUserId contains all the Ids of the previously selected filters
    foreach (string selectedUserId in indexUserInteractionViewModel.SelectedUserId)
    {
        if (userInteraction.AspNetUsers_Id.Equals(selectedUserId))
            // ...
    }
}

And the View:

<script type="text/javascript">

    $(document).ready(function () {
        $('.selectpicker').selectpicker();
    });

</script>

<th>@Html.DropDownListFor(Model => Model.SelectedUserId, Model.AvailableUser_ID as MultiSelectList, new { @id = "userFilter", @class = "selectpicker", @multiple = "mulitple", data_live_search = "true" })</th>

So how can I keep the Selection selected?

Unfortunately I have little js-knowledge and i am assuming that i could solve it in the js-script. I am hoping for some experts here. Thank you!


Solution

  • A colleague of mine found a solution, this is what works:

            var selectedList = @Html.Raw(Json.Encode(Model.SelectedUserId));
            if(selectedList.length > 0){
                var result = '[';
                for (i = 0; i < selectedList.length; i++) {
                    result += '"' + selectedList[i] + '",';
                }
                result = result.slice(0, -1); //remove last comma
                result += ']';
    
                $('.selectpicker').selectpicker('val', JSON.parse(result1));
            }else{
                $('.selectpicker').selectpicker();
            }