如何在MVC上移动两个列表框之间的项目 – JQuery无法正常工作

我已经查看了其他SO主题,他们最终要么真的老了,要么使用WebForms。 我有一个MVC视图,其中我有两个列表框。 我想在两个列表框之间来回移动项目。 观点是:

@using (Html.BeginForm()) { @Html.ListBoxFor(m => m.SelectedAttributes, Model.Attributes, new {id="listBoxAvail", SIZE = 5} )   @Html.ListBoxFor(m => m.SelectedAttributes2, Model.SelectedItems, new { id = "listBoxSel", SIZE = 5}) } 

ViewModel是:

  public class OptInViewModel { public IEnumerable SelectedAttributes { get; set; } public IEnumerable SelectedAttributes2 { get; set; } public IEnumerable Attributes { get; set; } public IEnumerable SelectedItems { get; set; } } And the Controller code is: public ActionResult Index() { AttributeEntities db = new AttributeEntities(); List listSelectListItems = new List(); List listSelItems = new List(); foreach (var attributes in db.HarmonyAttributes) { SelectListItem selectList = new SelectListItem { Text = attributes.AttributeName, Value = attributes.AtrributeLabel, Selected = false }; listSelectListItems.Add(selectList); } foreach (var sel in db.SelectedHarmonyAttributes) { SelectListItem selList = new SelectListItem { Text = sel.CustomLabel, Value = sel.HarmonyAttribute_ID.ToString(), Selected = false }; listSelectListItems.Add(selList); } OptInViewModel viewModel = new OptInViewModel { Attributes = listSelectListItems, SelectedItems = listSelItems }; return View(viewModel); } 

我使用JQuery尝试这样做但它没有工作(没有任何东西被转移到第二个列表框)。 谁知道什么是错的?

   $(function () { $("add").click(function () { $("#listBoxAvail > option:selected").each(function () { $(this).remove().appendTo("#listBoxSel"); }); }); $("remove").click(function () { $("#listBoxSel > option:selected").each(function () { $(this).remove().appendTo("#listBoxAvail"); }); }); });  

将按钮类型从提交更改为按钮,如下所示

   

在你的JavaScript正确的选择器前面添加#到id,它应该工作!

$("add")$("#add")

$("remove")$("#remove")

如果你想要你可以减少它

   

您可以使用jQuery-Dual-Listbox插件。 它需要一些设置,但在MVC环境中运行良好。 需要注意的是,为了将第二个列表框中的选定值发布回服务器进行处理,您需要确保在提交表单之前selected该列表框中的所有项目。

例如,为你的标记:

   

资源