Bootstrap Selectpicker 多选提交后不保留选择

Bootstrap Selectpicker multiselect doesn't keep selection after submit

我正在使用 bootstrap 选择器的多选下拉菜单来过滤 mvc5 网络应用程序中 table 的项目。到目前为止一切正常,但我无法在提交后保持选定的过滤器被选中。所以我可以在控制器中读取选定的过滤器,但在那之后,只有第一个先前选择的过滤器在提交后仍然显示为已选择。我希望所有选定的过滤器仍处于选中状态。我怎样才能做到这一点?

这是我的代码,ViewModel 包含:

        public MultiSelectList AvailableUser_ID { get; set; }

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

控制器(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))
            // ...
    }
}

和视图:

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

那么我怎样才能让选择保持选中状态?

不幸的是,我的 js 知识很少,我假设我可以在 js 脚本中解决它。我希望这里有一些专家。谢谢!

我的一位同事找到了解决方案,这是可行的:

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