在Html.DropDownlistFor中获取多个选定值

@Html.DropDownListFor(m => m.branch, CommonMethod.getBranch("",Model.branch), "--Select--", new { @multiple = "multiple" }) @Html.DropDownListFor(m => m.division, CommonMethod.getDivision(Model.branch,Model.division), "--Select--", new { @multiple = "multiple" }) 

我有两个DropDownListFor实例。 我想将之前存储为Model.branch和Model.division的值设置为true。 这些是存储的id的字符串数组

 class CommonMethod { public static List getDivision(string [] branchid , string [] selected) { DBEntities db = new DBEntities(); List division = new List(); foreach (var b in branchid) { var bid = Convert.ToByte(b); var div = (from d in db.Divisions where d.BranchID == bid select d).ToList(); foreach (var d in div) { division.Add(new SelectListItem { Selected = selected.Contains(d.DivisionID.ToString()), Text = d.Description, Value = d.DivisionID.ToString() }); } } } return division; } } 

对于模型中的选定项,将返回的除法值选择为true,但在视图侧,则不选择它。

使用ListBoxFor而不是DropDownListFor

 @Html.ListBoxFor(m => m.branch, CommonMethod.getBranch("", Model.branch), "--Select--") @Html.ListBoxFor(m => m.division, CommonMethod.getDivision(Model.branch, Model.division), "--Select--") 

branchdivision属性显然必须是包含所选值的集合。

以及使用视图模型构建多选下拉列表的正确方法的完整示例:

 public class MyViewModel { public int[] SelectedValues { get; set; } public IEnumerable Values { get; set; } } 

将在控制器中填充:

 public ActionResult Index() { var model = new MyViewModel(); // preselect items with values 2 and 4 model.SelectedValues = new[] { 2, 4 }; // the list of available values model.Values = new[] { new SelectListItem { Value = "1", Text = "item 1" }, new SelectListItem { Value = "2", Text = "item 2" }, new SelectListItem { Value = "3", Text = "item 3" }, new SelectListItem { Value = "4", Text = "item 4" }, }; return View(model); } 

并在视图中:

 @model MyViewModel ... @Html.ListBoxFor(x => x.SelectedValues, Model.Values) 

HTML助手将自动预选其值与SelectedValues属性匹配的项目。

对我来说,它也适用于@Html.DropDownListFor

模型:

 public class MyViewModel { public int[] SelectedValues { get; set; } public IEnumerable Values { get; set; } } 

控制器:

 public ActionResult Index() { var model = new MyViewModel(); // the list of available values model.Values = new[] { new SelectListItem { Value = "2", Text = "2", Selected = true }, new SelectListItem { Value = "3", Text = "3", Selected = true }, new SelectListItem { Value = "6", Text = "6", Selected = true } }; return View(model); } 

剃刀:

 @Html.DropDownListFor(m => m.SelectedValues, Model.Values, new { multiple = "true" }) 

在控制器中提交的SelectedValues看起来像:

在此处输入图像描述 在此处输入图像描述