0

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

这是我的代码,ViewModel 包含:

        public MultiSelectList AvailableUser_ID { get; set; }

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

控制器(职位):

[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 脚本中解决它。我希望这里有一些专家。谢谢!

4

1 回答 1

0

我的一位同事找到了一个解决方案,这是有效的:

        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();
        }
于 2017-05-26T19:10:30.793 回答