在两个列表框之间移动项目后保持默认顺序

时间:2018-11-26 11:39:23

标签: javascript c# html asp.net-mvc listbox

因此,我初始化了两个列表框,一个用于选择的选项,另一个用于可用的选项,并将数据填充到其中,如下所示:

HTML

@Html.ListBox("selectedOptions", (MultiSelectList) ViewBag.selSectOpts, new {@class = "form-control", style="height:200px"}
@Html.ListBox("availOptions", (MultiSelectList) ViewBag.availSectOpts, new {@class = "form-control", style="height:200px"})

C#

private void PopulateAssignedSectorData(Agency agency)
{        
        var allSectors = _db.Sectors.Where(s => s.deleted == false).OrderBy(s => s.name);
        var availableSectors = new HashSet<int>(agency.Sectors.Select(b => b.id));
        var viewModelAvailable = new List<AgencySectorViewModel>();
        var viewModelSelected = new List<AgencySectorViewModel>();
        foreach (var sector in allSectors)
        {
            if (availableSectors.Contains(sector.id))
            {
                viewModelSelected.Add(new AgencySectorViewModel
                {
                    SectorID = sector.id,
                    SectorName = sector.name,
                    //Assigned = true
                });
            }
            else
            {
                viewModelAvailable.Add(new AgencySectorViewModel
                {
                    SectorID = sector.id,
                    SectorName = sector.name,
                    //Assigned = false
                });
            }
        }

        ViewBag.selSectOpts = new MultiSelectList(viewModelSelected, "SectorID", "SectorName");
        ViewBag.availSectOpts = new MultiSelectList(viewModelAvailable, "SectorID", "SectorName");
}

JS

$('#selectedOptions').change(function (e) {
    var selectedOpts = $('#selectedOptions option:selected');

    $('#availOptions').append($(selectedOpts));
    $(selectedOpts).remove();
    e.preventDefault();


});

$('#availOptions').change(function (e) {
    var selectedOpts = $('#availOptions option:selected');
    $('#selectedOptions').append($(selectedOpts));
    $(selectedOpts).remove();
    e.preventDefault();
});

我的问题是,当我在两个列表框之间移动项目时,第一个列表框的项目插入到第二个列表框的底部,反之亦然。

我希望能够保持原始顺序,而且我也不知道该如何处理,因为我的两个列表都是基于查询自定义的。非常感谢您的帮助。

0 个答案:

没有答案