从列表框(使用 Ajax 填充)中获取所选项
本文关键字:获取 选项 填充 Ajax 列表 使用 | 更新日期: 2023-09-27 18:31:23
我正在尝试从我的多选列表中获取选定的项目/项目。我真正关心检索的只是所选项目之一或所选组,但组中的所有项目就足够了。我的列表开始时为空,然后在使用 Ajax 选择不同的列表后填充。
我的 JQuery 更改事件是这样的:
$("#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');
这调用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();
在我看来,我像这样显示此列表:
@Html.LabelFor(m => m.CreateModel.FamilyGroups)
@Html.ListBoxFor(m => m.CreateModel.SelectedFamilyGroupId, Model.CreateModel.FamilyGroups, new {@class="form-control", @id="family-select"})
我的ViewModel
是这样的:
[Display(Name="Family in Study")]
public IEnumerable<SelectListItem> FamilyGroups { get; set; }
public IEnumerable<SelectListItem> SelectedFamilyGroupId { get; set; }
我通过将SelectedFamilyGroupId
类型更改为IEnumerable<string>
来解决此问题