ListBox为了不让我选择多个项目MVC

当我运行代码时,我一次只能选择一个项目,这很奇怪,因为’ListBoxFor()’用于选择多个项目,所以我想要的是:

选择多个项目

查看(Index.cshtml):

@Html.ListBoxFor(m => m.DropDownItems, new MultiSelectList(Repository.DDFetchItems(), "Value", "Text", Model.DropDownItems))

Model(ModelVariables.cs):

 public class ModelVariables { public List DropDownItems { get; set; } } public static class Repository { public static List DDFetchItems() { return new List() { new SelectListItem(){ Text = "Dogs", Value = "1", Selected = true}, new SelectListItem(){ Text = "Cats", Value = "2"}, new SelectListItem(){ Text = "Death", Value = "3"} }; } } 

Controller(HomeController.cs):

 [HttpGet] public ActionResult Index() { ModelVariables model = new ModelVariables() { DropDownItems = Repository.DDFetchItems() }; return View(model); } 

您不能将绑定到复杂对象的集合(这是List )。 回发一组简单值(在您的情况下,如果您选择第一个和第三个选项,它将提交[1, 3] (所选选项的值)。

您的模型需要一个IEnumerable属性来绑定。

 public class ModelVariables { public IEnumerable SelectedItems { get; set; } public IEnumerable DropDownItems { get; set; } } 

然后在GET方法中

 public ActionResult Index() { var ModelVariables= new ModelVariables() { DropDownItems = Repository.DDFetchItems(), SelectedItems = new List(){ 1, 3 } // to preselect the 1st and 3rd options }; return View(model); } 

并在视图中

 @Html.ListBoxFor(m => m.SelectedItems, Model.DropDownItems) 

旁注

  1. DDFetchItems()方法中删除Selected = true – 它被DDFetchItems()方法忽略,因为它绑定到的属性的值决定了所选的内容
  2. 无需从ListBoxFor()方法中的第一个构建新的相同SelectList (属性DropDownItems已经是IEumerable