越来越多选择的价值观Html.DropDownlistFor [英] Getting Multiple Selected Values in 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的两个实例。我想设置选作如此那些有pviously存储值Model.branch和Model.division $ P $。这些存储的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--")
的分支
和分工
属性必须显然是集合将包含选定的值。
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帮手会自动preSELECT其值的项目匹配的 SelectedValues
属性。
这篇关于越来越多选择的价值观Html.DropDownlistFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!