简体   繁体   English

从ListBox中获取选定的项目(由Ajax填充)

[英]Get selected items from ListBox (populated with Ajax)

I am trying to get the selected item / items from my multiselect list. 我正在尝试从多选列表中获取选定的一个或多个项目。 All I really care to retrieve is one of the selected items or the selected group, but all of the items in the group would suffice. 我真正想要检索的只是所选项目之一或所选组,但是该组中的所有项目就足够了。 My list starts off as empty and then is populated after a selection of a different list using Ajax. 我的列表开始为空,然后使用Ajax选择其他列表后填充。

My JQuery change event is like so: 我的JQuery change事件是这样的:

$("#institutions").change(function() {
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("FillGroupsAndFam")',
                    dataType: 'json',
                    data: { institutionId: Number($("#institutions").val()) },
                    success: function(model) {
                        $("#family-select").empty();
                        var $prevGroup, prevGroupName;
                        $.each(model.FamilyGroups, function() {                              
                            if (prevGroupName != this.Group.Name) {
                                $prevGroup = $(document.createElement("optgroup"))
                                .prop("label", this.Group.Name)
                                .appendTo("#family-select");
                            }
                                $(document.createElement("option"))
                                    .val(this.Value)
                                    .text(this.Text)
                                    .appendTo("#family-select");
                            prevGroupName = this.Group.Name;
                        });
                        $("#family-select").multiselect('rebuild');

This calls FillGroupsAndFam which populates my list like so: 这将调用FillGroupsAndFam ,它会像这样填充我的列表:

     var famList = (from f in fam
        let famGroup = new SelectListGroup {Name = f.FamilyGroupName}
        from id in f.UserIds
        select new SelectListItem
        {
            Text = UserManager.FindById(id).UserName, Value = id, Disabled = true, Group = famGroup
        }).ToList();

In my view I am displaying this list like this: 在我看来,我正在显示以下列表:

    @Html.LabelFor(m => m.CreateModel.FamilyGroups)
    @Html.ListBoxFor(m => m.CreateModel.SelectedFamilyGroupId, Model.CreateModel.FamilyGroups, new {@class="form-control", @id="family-select"})

And my ViewModel has this: 而我的ViewModel具有:

[Display(Name="Family in Study")]
public IEnumerable<SelectListItem> FamilyGroups { get; set; }
public IEnumerable<SelectListItem> SelectedFamilyGroupId { get; set; }

我通过将SelectedFamilyGroupId类型更改为IEnumerable<string>来解决此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM