问题描述
@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 的字符串数组
I have two instances of DropDownListFor. I want to set selected as true for those which have previously stored values for Model.branch and Model.division. These are string arrays of stored ids
class CommonMethod
{
public static List<SelectListItem> getDivision(string [] branchid , string [] selected)
{
DBEntities db = new DBEntities();
List<SelectListItem> division = new List<SelectListItem>();
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;
}
}
对于模型中的选定项,除法的返回值选择为真,但在视图侧未选择.
The returned value of division is selected as true for the selected item in the model, but on view side it is not selected.
推荐答案
使用 ListBoxFor
而不是 DropDownListFor
:
@Html.ListBoxFor(m => m.branch, CommonMethod.getBranch("", Model.branch), "--Select--")
@Html.ListBoxFor(m => m.division, CommonMethod.getDivision(Model.branch, Model.division), "--Select--")
branch
和 division
属性显然必须是包含所选值的集合.
The branch
and division
properties must obviously be collections that will contain the selected values.
以及使用视图模型构建多选下拉列表的正确方法的完整示例:
And a full example of the proper way to build a multiple select dropdown using a view model:
public class MyViewModel
{
public int[] SelectedValues { get; set; }
public IEnumerable<SelectListItem> 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
属性匹配的项目.
It is the HTML helper that will automatically preselect the items whose values match those of the SelectedValues
property.
这篇关于在 Html.DropDownlistFor 中获取多个选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!