我正在使用bootstrap selectpicker进行多选下拉菜单来过滤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-script中解决它。我希望这里有一些专家。谢谢!
答案 0 :(得分: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();
}